CSRF token generation and verification
Protect state-changing forms with a per-session token compared in constant time.
- PHP
- GreenSnippets
- MIT
- Executed with PHP 8.2
<?php
function csrfToken(array &$session): string
{
if (empty($session['csrf'])) {
$session['csrf'] = bin2hex(random_bytes(32));
}
return $session['csrf'];
}
function csrfVerify(array $session, ?string $submitted): bool
{
return isset($session['csrf'], $submitted) && hash_equals($session['csrf'], $submitted);
}Example / expected output
// In the form: <input type="hidden" name="csrf" value="<?= htmlspecialchars(csrfToken($_SESSION)) ?>">
// On submission: if (!csrfVerify($_SESSION, $_POST['csrf'] ?? null)) { http_response_code(403); exit; }How it works
Generate one token per session, embed it in every form as a hidden field and verify it on POST. hash_equals avoids timing leaks. The helpers take the session array as a parameter (pass $_SESSION), which keeps them testable. Also set SameSite on your session cookie for defense in depth.
Related snippets
- PHP Tested
Validate emails and URLs in PHP
Use filter_var to validate email addresses and http(s) URLs, with an allow-list for schemes.
- Python Tested
Sign API requests with HMAC-SHA256
Create and verify a timestamped signature over the method, path and body so requests cannot be forged or replayed.
- JavaScript Tested
Generate secure random IDs and integers
Create UUIDs, random integers in a range and URL-safe tokens with the Web Crypto API instead of Math.random.
- PHP Tested
Generate a secure random token in PHP
Create unpredictable tokens for password resets, API keys and CSRF protection with random_bytes.

