PHP
Implement CSRF Protection with Anti-CSRF Tokens
Protect web forms from Cross-Site Request Forgery (CSRF) attacks by generating and validating unique, unpredictable tokens for each submission.
<?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 (!isset($_SESSION['csrf_token']) || !hash_equals($_SESSION['csrf_token'], $token)) {
// Token mismatch or missing
return false;
}
// Token matches, invalidate it to prevent reuse (optional, for one-time tokens)
unset($_SESSION['csrf_token']);
return true;
}
// --- Usage Example ---
// 1. On the page rendering the form (GET request)
// Inject the token into a hidden field
$csrfToken = generateCsrfToken();
echo '<form action="submit.php" method="POST">';
echo '<input type="hidden" name="csrf_token" value="' . htmlspecialchars($csrfToken) . '">';
echo '<input type="text" name="data" placeholder="Enter data">';
echo '<button type="submit">Submit</button>';
echo '</form>';
// 2. On the form submission handler (POST request - e.g., submit.php)
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['csrf_token'])) {
if (validateCsrfToken($_POST['csrf_token'])) {
echo "Form submitted successfully (CSRF token valid)!
";
// Process form data securely
// e.g., $data = htmlspecialchars($_POST['data']);
} else {
http_response_code(403);
echo "Error: Invalid CSRF token.
";
}
} else if ($_SERVER['REQUEST_METHOD'] === 'POST') {
http_response_code(403);
echo "Error: CSRF token missing.
";
}
?>
How it works: This snippet outlines a method to implement Cross-Site Request Forgery (CSRF) protection using anti-CSRF tokens in PHP. A unique, unpredictable token is generated and stored in the user's session. This token is then embedded as a hidden field in forms. Upon form submission, the server validates the received token against the one stored in the session. If they don't match, the request is rejected, preventing malicious requests from being executed without the user's explicit intent, as an attacker cannot guess the unique token.