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 common issues with json_encode in PHP when handling special characters like umlauts?
- What are the advantages of switching from the provided MySQLi class to PDO for database operations in PHP?
- Are there any best practices for writing conditional statements in PHP to avoid errors like the one mentioned in the thread?