PHP
Implementing CSRF Protection with PHP Sessions
Protect your PHP web applications from Cross-Site Request Forgery (CSRF) attacks by generating and validating unique tokens stored in user sessions for form submissions.
<?php
session_start();
// Function to generate a new 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 is valid, clear it after use to prevent replay attacks (optional but recommended for single-use tokens)
unset($_SESSION['csrf_token']);
return true;
}
return false;
}
// --- Usage Example ---
// 1. On your form page (e.g., index.php or form.html with PHP embedded):
// <form action="process.php" method="POST">
// <input type="hidden" name="csrf_token" value="<?php echo htmlspecialchars(generateCsrfToken()); ?>">
// <input type="text" name="data" placeholder="Your Data">
// <button type="submit">Submit</button>
// </form>
// 2. In your processing script (e.g., process.php):
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
if (isset($_POST['csrf_token'])) {
if (validateCsrfToken($_POST['csrf_token'])) {
echo "Form submitted successfully and CSRF token validated!
";
// Process your form data here
// For example: var_dump($_POST['data']);
} else {
// CSRF token mismatch or missing
header('HTTP/1.1 403 Forbidden');
die('Invalid CSRF token.');
}
} else {
// CSRF token missing in request
header('HTTP/1.1 403 Forbidden');
die('CSRF token missing.');
}
} else {
// Handle GET requests if necessary or redirect
echo "This is a form processing endpoint. Please submit a POST request.
";
}
// Example of generating token for display (uncomment to see output on initial load)
// echo "Current CSRF Token: " . generateCsrfToken() . "
";
?>
How it works: This PHP snippet outlines how to implement Cross-Site Request Forgery (CSRF) protection using session-based tokens. `generateCsrfToken()` creates a unique, cryptographically secure token and stores it in the user's session, which is then embedded into forms as a hidden input. `validateCsrfToken()` compares the submitted token with the one in the session. If they match, the request is deemed legitimate. Using `hash_equals()` prevents timing attacks, and unsetting the token after use prevents replay attacks, enhancing form submission security.