PHP
Implement CSRF Protection Using Synchronizer Tokens
Safeguard your web forms from Cross-Site Request Forgery (CSRF) attacks by generating unique, session-based tokens and validating them upon form submission.
<?php
session_start();
// --- 1. Generate and store CSRF token ---
if (empty($_SESSION['csrf_token'])) {
$_SESSION['csrf_token'] = bin2hex(random_bytes(32)); // Generate a cryptographically secure token
}
$csrfToken = $_SESSION['csrf_token'];
// --- 2. HTML Form embedding the token ---
if ($_SERVER['REQUEST_METHOD'] === 'GET') {
echo <<<HTML
<form action="" method="POST">
<label for="message">Your Message:</label><br>
<input type="text" id="message" name="message" value="Hello World"><br><br>
<input type="hidden" name="csrf_token" value="{$csrfToken}">
<input type="submit" value="Submit">
</form>
HTML;
}
// --- 3. Validate CSRF token on POST submission ---
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
if (!isset($_POST['csrf_token']) || !hash_equals($_SESSION['csrf_token'], $_POST['csrf_token'])) {
// CSRF token mismatch or missing
http_response_code(403);
die('CSRF token validation failed. Request blocked.');
}
// Token is valid, process the form data securely
$message = htmlspecialchars($_POST['message'] ?? 'No message provided');
echo "Form submitted successfully! Message: {$message}
";
// Optional: Regenerate token after successful use to prevent replay attacks
unset($_SESSION['csrf_token']);
$_SESSION['csrf_token'] = bin2hex(random_bytes(32));
}
?>
How it works: Cross-Site Request Forgery (CSRF) attacks trick authenticated users into submitting unintended requests. CSRF tokens mitigate this by requiring a unique, secret token in every sensitive form submission. This snippet generates a cryptographically secure token, stores it in the user's session, embeds it as a hidden field in the HTML form, and then validates it upon submission. The `hash_equals()` function is used for constant-time comparison, preventing timing attacks. Regenerating the token after use adds another layer of security against token reuse.