Generate a token
if (empty($_SESSION['csrf_token'])) {
$_SESSION['csrf_token'] = bin2hex(random_bytes(32));
}
Include it in a form
<input type="hidden" name="csrf_token"
value="<?= htmlspecialchars($_SESSION['csrf_token'], ENT_QUOTES, 'UTF-8') ?>">
Verify submitted tokens
$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.');
}
Apply protection consistently
Protect profile updates, password changes, administrative actions, and other state-changing operations. Do not use GET requests to modify data.
Set appropriate SameSite, Secure, and HttpOnly cookie attributes as defense in depth. Define an explicit CSRF strategy for APIs based on how credentials are transported.