PHP
Implement CSRF Protection with Tokens in PHP
Protect your web applications from Cross-Site Request Forgery (CSRF) attacks by generating and validating unique tokens for state-changing requests 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 (!isset($_SESSION['csrf_token']) || $token !== $_SESSION['csrf_token']) {
// Token is invalid or missing
return false;
}
// Token is valid, unset to prevent replay attacks (optional, depending on flow)
// 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(); ?>">
// <!-- other form fields -->
// <button type="submit">Submit</button>
// </form>
// Example usage in process.php:
// if ($_SERVER['REQUEST_METHOD'] === 'POST') {
// if (validateCsrfToken($_POST['csrf_token'] ?? '')) {
// // Process the request
// echo "Request processed securely!";
// } else {
// // CSRF attack detected!
// die("CSRF token validation failed.");
// }
// }
?>
How it works: This PHP snippet demonstrates how to implement Cross-Site Request Forgery (CSRF) protection using synchronized tokens. `generateCsrfToken()` creates a unique, cryptographically secure token stored in the user's session and embeds it in forms. `validateCsrfToken()` then verifies if the submitted token matches the one in the session. This prevents attackers from forging requests on behalf of authenticated users, as they cannot predict or obtain the valid token.