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');
}
}
Related Questions
- What are some considerations for handling multiple data entries simultaneously in PHP to avoid issues like lost updates or data inconsistency?
- How can the user troubleshoot and verify the value of the $absender variable before sending the email?
- What are the potential performance implications of storing XML data in a PHP session array for repeated search operations?