PHP
Implement CSRF Protection with Synchronizer Tokens
Protect your web forms from Cross-Site Request Forgery (CSRF) attacks by generating and validating unique synchronizer tokens for each user session in PHP.
<?php
session_start();
// Function to generate a CSRF token
function generateCsrfToken() {
if (empty($_SESSION['csrf_token'])) {
$_SESSION['csrf_token'] = bin2hex(random_bytes(32));
}
return $_SESSION['csrf_token'];
}
// Function to validate a CSRF token
function validateCsrfToken($token) {
if (!empty($_SESSION['csrf_token']) && hash_equals($_SESSION['csrf_token'], $token)) {
// Token is valid, unset to prevent replay attacks (optional, depending on use case)
unset($_SESSION['csrf_token']);
return true;
}
return false;
}
// --- Example Usage ---
// 1. On a page with a form:
$csrfToken = generateCsrfToken();
echo '<form action="process_form.php" method="POST">';
echo '<input type="hidden" name="csrf_token" value="' . $csrfToken . '">';
echo '<label for="data">Enter Data:</label>';
echo '<input type="text" id="data" name="data">';
echo '<button type="submit">Submit</button>';
echo '</form>';
// 2. In process_form.php (or the same script if handling submission):
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
if (!isset($_POST['csrf_token']) || !validateCsrfToken($_POST['csrf_token'])) {
die('CSRF token validation failed!');
}
// If validation passes, process the form data
echo "Form processed successfully!";
// var_dump($_POST['data']);
}
?>
How it works: This PHP snippet demonstrates how to implement Cross-Site Request Forgery (CSRF) protection using synchronizer tokens. A unique token is generated and stored in the user's session (`$_SESSION['csrf_token']`). This token is then embedded as a hidden field in forms. Upon form submission, the submitted token is compared against the one stored in the session. If they match, the request is deemed legitimate. The `hash_equals` function is used for constant-time comparison to prevent timing attacks. After successful validation, the token is optionally unset to prevent replay attacks, especially for single-use forms.