Generate a token
<?php
session_start();
if (empty($_SESSION['csrf_token'])) {
$_SESSION['csrf_token'] = bin2hex(random_bytes(32));
}
Include it in the form
<input
type="hidden"
name="csrf_token"
value="<?= htmlspecialchars($_SESSION['csrf_token'], ENT_QUOTES, 'UTF-8') ?>"
>
Validate on submission
<?php
session_start();
$submitted = $_POST['csrf_token'] ?? '';
$stored = $_SESSION['csrf_token'] ?? '';
if (!is_string($submitted) ||
!is_string($stored) ||
$stored === '' ||
!hash_equals($stored, $submitted)) {
http_response_code(403);
exit('Invalid request token.');
}
Important
Use CSRF protection for state-changing actions, including account changes and administrative operations. SameSite cookies are useful defense-in-depth, not a universal replacement for tokens.