PHP
Implementing CSRF Protection with Session Tokens in PHP
Protect your web forms and API endpoints from Cross-Site Request Forgery (CSRF) attacks by generating and validating unique, session-bound tokens in PHP.
<?php
session_start();
// --- Generate CSRF Token ---
function generateCsrfToken() {
if (empty($_SESSION['csrf_token'])) {
$_SESSION['csrf_token'] = bin2hex(random_bytes(32));
}
return $_SESSION['csrf_token'];
}
// --- Validate CSRF Token ---
function validateCsrfToken($token) {
if (!isset($_SESSION['csrf_token']) || !hash_equals($_SESSION['csrf_token'], $token)) {
// Log this attempt, redirect, or deny the request
// For example:
// error_log("CSRF token mismatch detected!");
// header('Location: /error.php?code=403');
// exit();
return false;
}
// Token is valid, clear it to prevent reuse (optional, but good for single-use forms)
// unset($_SESSION['csrf_token']);
return true;
}
// Example Usage (in a form):
// <form action="process.php" method="POST">
// <input type="hidden" name="csrf_token" value="<?php echo generateCsrfToken(); ?>">
// <input type="text" name="data">
// <button type="submit">Submit</button>
// </form>
// Example Usage (in process.php):
// if ($_SERVER['REQUEST_METHOD'] === 'POST') {
// $receivedToken = $_POST['csrf_token'] ?? '';
// if (validateCsrfToken($receivedToken)) {
// // Process the request
// echo "Request processed securely!";
// } else {
// echo "CSRF token invalid!";
// }
// }
How it works: This PHP snippet demonstrates how to implement Cross-Site Request Forgery (CSRF) protection using session-bound tokens. The `generateCsrfToken` function creates a unique token stored in the user's session and outputs it into an HTML form as a hidden field. The `validateCsrfToken` function then compares the token received from the submitted form with the one stored in the session. If they don't match, or if no token exists, the request is deemed fraudulent and rejected, preventing attackers from tricking users into making unintended actions.