What are best practices for validating and comparing tokens in PHP to prevent CSRF vulnerabilities?
CSRF (Cross-Site Request Forgery) vulnerabilities can be prevented by using tokens to validate and compare requests. One best practice is to generate a unique token for each form submission and store it in a session variable. When a form is submitted, compare the token from the form with the one stored in the session to ensure they match.
// Generate a CSRF token and store it in a session variable
if (!isset($_SESSION['csrf_token'])) {
$_SESSION['csrf_token'] = bin2hex(random_bytes(32));
}
// Include this token in your form
<input type="hidden" name="csrf_token" value="<?php echo $_SESSION['csrf_token']; ?>">
// Validate the token when the form is submitted
if ($_POST['csrf_token'] !== $_SESSION['csrf_token']) {
// Token mismatch, handle error or reject the request
die('CSRF token validation failed');
}