PHP form token verification to prevent CSRF attacks

In PHP, form tokens are a security mechanism used to prevent Cross-Site Request Forgery (CSRF) attacks.

CSRF attack is an attack method that uses user identity to perform illegal operations without authorization.

The principle of form token is to generate a random token in the form and store it on the server side.

When the form is submitted, the token is sent to the server along with the form data. After receiving the form data, the server side

Check whether the token is valid, and refuse to process the request if it is invalid. The method of generating form token can use PHP's built-in function csrf_token(). Here is an example:

session_start();
function csrf_token()
{
    if (empty($_SESSION['csrf_token'])) {
        $_SESSION['csrf_token'] = bin2hex(random_bytes(32));
    }
    return $_SESSION['csrf_token'];
}
function validate_csrf_token($token) {
    if (empty($_SESSION['csrf_token']) || $_SESSION['csrf_token'] !== $token) {
        return false;
    }
    return true;
}
// 验证表单提交的token
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $submitted_token = $_POST['csrf_token'];
    if (!validate_csrf_token($submitted_token)) {
        die('Invalid CSRF token');
    }
    // 处理表单数据
    echo '提交成功';
}


// 在表单中使用token
$token = csrf_token();
echo '<form action="" method="post">';
echo '<input type="hidden" name="csrf_token" value="' . $token . '">';
echo '<input type="text" name="name">';
echo '<input type="submit" value="Submit">';
echo '</form>';

 

Guess you like

Origin blog.csdn.net/weixin_39934453/article/details/132760741