Development
How to Add CSRF Protection to PHP Forms

CSRF protection prevents another site from using a visitor's existing authenticated browser session to submit an unwanted state-changing request. For a conventional PHP form, generate a random token, store it in the session, place it in the form, and verify it before performing the action.
This example assumes PHP 8.1 or newer, HTTPS, and a correctly configured session started before output. It protects a session-authenticated form; it is not a replacement for authentication or authorization.
Generate a session-bound CSRF token
Create the token once per session unless your application has a reason to rotate it more often. Rotating on every render can invalidate another open tab.
<?php
/** Return a random token associated with the active session. */
function csrfToken(): string
{
if (!isset($_SESSION['csrf']) || !is_string($_SESSION['csrf'])) {
$_SESSION['csrf'] = bin2hex(random_bytes(32));
}
return $_SESSION['csrf'];
}
PHP's random_bytes provides cryptographically secure random bytes. Do not derive the token from an email address, timestamp, or predictable identifier.
Render it as an escaped hidden field:
<input type="hidden" name="csrf" value="<?= htmlspecialchars(csrfToken(), ENT_QUOTES, 'UTF-8') ?>">
Keep tokens out of URLs, analytics payloads, and application logs. A URL can leak through browser history and referrers.
Verify before changing state
The receiving endpoint must check the request method and token before saving data, sending email, or calling a remote API.
<?php
/** Reject a mutation without the active session's exact token. */
function requireCsrfToken(array $input): void
{
$expected = $_SESSION['csrf'] ?? null;
$actual = $input['csrf'] ?? null;
if (!is_string($expected) || !is_string($actual)
|| $expected === '' || !hash_equals($expected, $actual)) {
http_response_code(403);
exit('The form expired. Reload the page and try again.');
}
}
if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
http_response_code(405);
header('Allow: POST');
exit;
}
requireCsrfToken($_POST);
The type checks reject array-shaped input cleanly. hash_equals compares the submitted value with the trusted token using a timing-safe comparison. Place the trusted string first.
After verification, validate the business fields and authorize the requested operation. A valid CSRF token from one user does not grant that user permission to edit another user's record.
Keep the surrounding browser policy consistent
Set Secure and HttpOnly session cookies and choose a suitable SameSite policy. SameSite reduces some cross-site requests but has behavior and deployment constraints; keep explicit token validation for session-authenticated mutations.
Do not perform mutations through GET links. Logout, deletion, and administrative changes should use an appropriate state-changing method with CSRF checks.
For JavaScript requests, send the token in a request header or body and validate it against the session. Do not enable permissive credentialed cross-origin access merely to make an integration work. APIs using explicit bearer tokens rather than ambient cookies have a different threat model.
The OWASP CSRF prevention guidance explains synchronizer tokens and related defenses. Cross-site scripting can still undermine token protection, so escape output and keep other security boundaries intact.
Test rejection paths as carefully as success
Verify that a correct token succeeds, while missing, incorrect, array-shaped, and different-session tokens fail before any mutation. Test an expired session and two simultaneously open forms. Confirm that the response does not expose the expected token.
A CSRF token is not an idempotency key. A legitimate user can submit a valid form twice; preventing duplicate business records requires a separate storage constraint or request identity.
For surrounding structure, see incremental PHP refactoring. Discuss a PHP security review when authentication and form handling have grown across several endpoints.