How does the CSRF token verification work in the PHP code for user authentication?

CSRF token verification is essential in user authentication to prevent cross-site request forgery attacks. The token is generated when the user logs in and is included in each form submission. The PHP code checks if the token in the form submission matches the one stored in the session to validate the request.

// Start the session
session_start();

// Generate CSRF token
if (!isset($_SESSION['csrf_token'])) {
    $_SESSION['csrf_token'] = bin2hex(random_bytes(32));
}

// Validate CSRF token
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    if (!hash_equals($_SESSION['csrf_token'], $_POST['csrf_token'])) {
        // Invalid CSRF token, handle the error
        die('CSRF token validation failed');
    }
}