How effective is the Synchronizer Tokens Strategy in preventing CSRF attacks in PHP?
CSRF attacks occur when a malicious website tricks a user's browser into making a request to a target website on which the user is authenticated. One way to prevent CSRF attacks in PHP is by using Synchronizer Tokens. This strategy involves generating a unique token for each user session and including it in forms. When a form is submitted, the server checks if the token in the request matches the one stored in the session, thereby verifying the authenticity of the request.
<?php
session_start();
function generateToken() {
$token = bin2hex(random_bytes(32));
$_SESSION['csrf_token'] = $token;
return $token;
}
function validateToken($token) {
return hash_equals($_SESSION['csrf_token'], $token);
}
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
if (!isset($_POST['csrf_token']) || !validateToken($_POST['csrf_token'])) {
die('CSRF token validation failed.');
}
// Process form data
}
$token = generateToken();
?>
<form method="post">
<input type="hidden" name="csrf_token" value="<?php echo $token; ?>">
<!-- Other form fields -->
<button type="submit">Submit</button>
</form>