How to protect a form with a CSRF token
Short answer
Store a random token in the session and put it into a hidden form field:
<?php
session_start();
$_SESSION['csrf'] ??= bin2hex(random_bytes(32));
echo '<input type="hidden" name="csrf" value="' . $_SESSION['csrf'] . '">';Checking on submission
Compare the submitted value with the stored one:
<?php
session_start();
if (!hash_equals($_SESSION['csrf'] ?? '', $_POST['csrf'] ?? '')) {
http_response_code(403);
exit('Invalid token');
}Why it matters
Without a token another site can submit the form on behalf of a logged-in user: the browser attaches their cookies by itself. The other site does not know the token.
Functions used in this recipe
- random_bytes — Returns cryptographically secure random bytes.
- hash_equals — Compares two strings in constant time.
- session_start — Starts a session or resumes the existing one.