The Analogy: The Signed Work Order and the Building's Standing Rules
A maintenance department will not act on just any instruction that arrives. To carry out a job -- move a machine, cut the power to a floor -- it demands a signed work order bearing a control number issued that morning to that specific team. An instruction phoned in by an outsider, however authoritative it sounds, is refused because it lacks the day's control number, which only the genuine team was given. A CSRF token is that control number: a secret value the server issued to this user's session and embedded in the form, so a state-changing request is honoured only if it carries the matching token. A forged request from another site cannot know it.
The reason this works is that the outsider can shout the instruction but cannot forge the control number. A cross-site attacker can make your browser send a request to your bank -- your browser will even attach your login cookie automatically -- but the attacker's page cannot read the secret token sitting in your bank's form, because the browser keeps sites isolated. So the request arrives with your cookie but without the token, and the server refuses it. This is precisely why CSRF protection is needed even when the user is logged in: authentication proves who you are, but the token proves the request actually originated from your session, not from a hostile page riding your cookie.
Beyond the per-job work order, the building also posts standing rules at every entrance: no unescorted visitors, fire doors stay shut, no tailgating. These blanket policies reduce whole classes of risk before any specific incident. Security headers are those standing rules -- Content-Security-Policy restricts where scripts may load from, X-Frame-Options forbids the page being embedded in a hostile frame, Strict-Transport-Security insists on HTTPS. Each is a one-line instruction to the browser that hardens the site against an entire category of attack.
The failure mode is twofold. A department that acts on unsigned instructions -- a state-changing endpoint with no token check -- can be driven by any hostile page the victim visits, which is CSRF itself. And a building that posts no standing rules leaves doors that should never be open: a site with no Content-Security-Policy lets an injected script load from anywhere, and one with no framing protection can be invisibly overlaid to trick users into clicking. Neither the per-request token nor the standing headers is sufficient alone; the token stops forged actions, the headers shrink the attack surface, and a secure site needs both, applied consistently, with no unguarded endpoint or missing rule.
Syntax or Core Structure
The synchronizer token pattern is the standard CSRF defence: issue a random token, embed it in the form, and verify it with a constant-time comparison on submit. Here a Csrf helper issues, renders, and checks the token.
<?php
declare(strict_types=1);
final class Csrf {
private string $token;
public function __construct() { $this->token = bin2hex(random_bytes(16)); }
public function token(): string { return $this->token; }
public function field(): string {
return '<input type="hidden" name="_token" value="' . $this->token . '">';
}
public function check(string $submitted): bool {
return hash_equals($this->token, $submitted);
}
}
$csrf = new Csrf();
echo 'token length: ', strlen($csrf->token()), "\n";
echo 'legit submit: ', ($csrf->check($csrf->token()) ? 'accepted' : 'rejected'), "\n";
echo 'forged submit: ', ($csrf->check('forged-value') ? 'accepted' : 'rejected'), "\n";
echo 'empty submit: ', ($csrf->check('') ? 'accepted' : 'rejected'), "\n";
Output:
token length: 32
legit submit: accepted
forged submit: rejected
empty submit: rejected
The constructor mints a 32-character token from random_bytes. field renders it as a hidden form input, and check compares a submitted value against the stored token with hash_equals. A submit carrying the correct token is accepted; a forged value and an empty value are both rejected. Because only pages served by your site can read the token to include it, a cross-site forgery -- which cannot read it -- always fails the check.
Technical Depth: Headers, SameSite, and Defence in Depth
The core security headers
A handful of response headers each shut down a class of attack. Sending them on every response is cheap and high-value.
| Header | Protects against |
|---|---|
Content-Security-Policy | XSS, unauthorised script/resource loads |
X-Frame-Options | Clickjacking via framing |
X-Content-Type-Options | MIME-sniffing attacks |
Referrer-Policy | Leaking URLs to other sites |
Strict-Transport-Security | Downgrade to plain HTTP |
<?php
declare(strict_types=1);
function securityHeaders(): array {
return [
'Content-Security-Policy' => "default-src 'self'",
'X-Frame-Options' => 'DENY',
'X-Content-Type-Options' => 'nosniff',
'Referrer-Policy' => 'no-referrer',
'Strict-Transport-Security' => 'max-age=31536000; includeSubDomains',
];
}
foreach (securityHeaders() as $name => $value) {
echo "$name: $value\n";
}
Output:
Content-Security-Policy: default-src 'self'
X-Frame-Options: DENY
X-Content-Type-Options: nosniff
Referrer-Policy: no-referrer
Strict-Transport-Security: max-age=31536000; includeSubDomains
Each entry is a header you would send with header("$name: $value") early in the response. default-src 'self' tells the browser to load scripts, styles, and other resources only from your own origin, neutralising most injected-script attacks. X-Frame-Options: DENY forbids framing, nosniff stops content-type guessing, no-referrer prevents URL leakage, and the HSTS header forces HTTPS for a year. Applying these centrally means every page is hardened by default.
SameSite cookies
The SameSite cookie attribute is a browser-level CSRF mitigation: it controls whether the session cookie is sent on cross-site requests at all. Modelling the rule clarifies why Lax (the modern default) blocks the dangerous cases.
<?php
declare(strict_types=1);
function cookieSent(string $sameSite, bool $crossSite, string $method): bool {
return match ($sameSite) {
'Strict' => !$crossSite,
'Lax' => !$crossSite || $method === 'GET',
'None' => true,
default => !$crossSite,
};
}
echo 'Strict, cross-site POST: ', cookieSent('Strict', true, 'POST') ? 'sent' : 'blocked', "\n";
echo 'Lax, cross-site POST: ', cookieSent('Lax', true, 'POST') ? 'sent' : 'blocked', "\n";
echo 'Lax, cross-site GET: ', cookieSent('Lax', true, 'GET') ? 'sent' : 'blocked', "\n";
echo 'Lax, same-site POST: ', cookieSent('Lax', false, 'POST') ? 'sent' : 'blocked', "\n";
Output:
Strict, cross-site POST: blocked
Lax, cross-site POST: blocked
Lax, cross-site GET: sent
Lax, same-site POST: sent
Strict never sends the cookie cross-site, maximally safe but it can break following links from other sites. Lax blocks the cookie on cross-site POST -- the CSRF-dangerous case -- while still sending it on a top-level cross-site GET, so ordinary links keep you logged in. Same-site requests always send it. This browser-enforced rule is a strong second layer beneath the token, which is why modern PHP defaults session cookies to Lax.
The double-submit cookie pattern
For stateless APIs that do not keep a server-side session token, the double-submit cookie pattern offers CSRF protection: the token is placed in both a cookie and a request header, and the server checks they match. A cross-site attacker can cause the cookie to be sent automatically but cannot read it to copy into the header, so the two cannot match.
<?php
declare(strict_types=1);
function csrfOk(string $cookieToken, string $headerToken): bool {
return $cookieToken !== '' && hash_equals($cookieToken, $headerToken);
}
$token = bin2hex(random_bytes(16));
echo 'legit (cookie==header): ', csrfOk($token, $token) ? 'accepted' : 'rejected', "\n";
echo 'forged (no header): ', csrfOk($token, '') ? 'accepted' : 'rejected', "\n";
echo 'mismatch: ', csrfOk($token, 'other') ? 'accepted' : 'rejected', "\n";
Output:
legit (cookie==header): accepted
forged (no header): rejected
mismatch: rejected
A legitimate JavaScript request reads the token from the cookie and echoes it in a custom header, so the two match and the request is accepted. A forged cross-site request has the cookie sent automatically but cannot set the custom header -- the same-origin policy stops the attacker's page from reading the cookie value -- so the header is empty and the check fails. A mismatched value is also rejected. This pattern trades the server-side token store for a check that both copies agree, which suits token-based and single-page-application architectures where there is no traditional session.
Real World Example: A CSRF-Protected Transfer Form
A money-transfer endpoint is the canonical CSRF target. The processor checks the token first, before any validation or action, then validates the inputs, and only then performs the transfer -- the correct order that ensures a forged request is stopped at the door.
<?php
declare(strict_types=1);
final class TransferForm {
public function __construct(private string $sessionToken) {}
/** @param array<string,string> $post */
public function handle(array $post): string {
$submitted = $post['_token'] ?? '';
if (!hash_equals($this->sessionToken, $submitted)) {
return '403: bad CSRF token';
}
$to = trim($post['to'] ?? '');
$amount = filter_var($post['amount'] ?? '', FILTER_VALIDATE_INT);
if ($to === '' || $amount === false || $amount <= 0) {
return '422: invalid input';
}
return "transferred $amount to $to";
}
}
$token = bin2hex(random_bytes(16));
$form = new TransferForm($token);
echo $form->handle(['_token' => $token, 'to' => 'ada', 'amount' => '50']), "\n";
echo $form->handle(['to' => 'attacker', 'amount' => '9999']), "\n";
echo $form->handle(['_token' => $token, 'to' => '', 'amount' => 'x']), "\n";
Output:
transferred 50 to ada
403: bad CSRF token
422: invalid input
The legitimate request carries the correct token and valid inputs, so the transfer proceeds. The forged cross-site request has no token, so it is rejected with 403 before any input is even examined -- the attacker's 9999 transfer never runs. The third request has the right token but invalid input, so it passes the CSRF gate and is stopped by validation with 422. Checking the token first means a forged request cannot reach the validation or action stages at all.
The design flaw is that a single per-session token, checked this way, is vulnerable to being leaked and reused, and does nothing about the token's lifetime or scope. If the token ever escapes -- through an XSS hole, a logged URL, or a referrer header on an external link -- an attacker can replay it for as long as the session lasts, because the same token is accepted for every form and never expires until logout. A stricter design scopes tokens more tightly: a per-request or per-form token that is consumed on use, so a captured token is already spent; or at minimum a token rotated periodically and bound to the specific action. There is also a subtle interaction with the earlier lessons: the token defends against CSRF but not XSS, and an XSS hole defeats CSRF protection entirely by reading the token straight out of the page -- which is why the security headers and output escaping from the previous lessons are not optional extras but part of the same defence. Relying on one long-lived token as if it were a complete solution, without the surrounding CSP, escaping, and SameSite cookie, is a common gap: CSRF tokens are one layer, and a layer assumed to be the whole wall is a flaw.
Common Mistakes
- No CSRF token on state-changing endpoints. Any POST that changes state without a token can be driven by a hostile page. Require and check a token on every such request.
- Checking the token after acting. Validating input or performing the action before the token check defeats the purpose. Check the token first, before anything else.
- Comparing tokens with
==. Naive comparison risks timing leaks. Usehash_equalsfor a constant-time comparison.
- Putting CSRF tokens on GET requests only. Safe (GET) requests should not change state and do not need a token; state changes belong on POST with a token. Do not protect the wrong verb.
- Relying on the token alone. An XSS hole can read the token and defeat CSRF protection. Pair tokens with CSP, output escaping, and
SameSite.
- Missing security headers. No CSP or framing protection leaves whole attack classes open. Send the core headers on every response.
- A too-permissive CSP.
unsafe-inlineor*sources gut the policy's value. Keep the policy as strict as the app allows.
- Forgetting
SameSiteon the session cookie. Without it, the cookie rides cross-site requests. SetSameSite=Lax(orStrict) plusSecureandHttpOnly.
- Long-lived, reusable tokens treated as complete. A single session-long token that never rotates can be replayed if leaked. Scope and rotate tokens, and treat them as one layer.
Best Practices
- Protect every state-changing endpoint with a CSRF token, checked with
hash_equalsbefore any validation or action.
- Reserve state changes for POST (and other unsafe verbs) with a token, keeping GET side-effect free.
- Send the core security headers -- CSP,
X-Frame-Options,nosniff,Referrer-Policy, HSTS -- on every response, centrally.
- Keep the Content-Security-Policy as strict as possible, avoiding
unsafe-inlineand wildcard sources.
- Set session cookies
SameSite=LaxorStrict, plusSecureandHttpOnly, as a second layer beneath the token.
- Treat CSRF tokens, headers, escaping, and cookie flags as one layered defence, never relying on any single one.
- Scope and rotate tokens where practical, so a leaked token cannot be replayed for the whole session.
- Remember that XSS defeats CSRF protection, so output escaping and CSP are part of the same effort, not separate concerns.
Practice Exercises
- Build a
Csrfhelper that issues a random token, renders a hidden field, and checks a submission withhash_equals, and show it accepting the right token and rejecting a forged and an empty one.
- Write a
securityHeadersfunction returning a map of the core security headers with sensible values, and print each as it would be sent.
- Model the
SameSitecookie rule forStrict,Lax, andNone, and demonstrate thatLaxblocks a cross-site POST but allows a cross-site GET and a same-site POST.
- Implement a form processor that checks the CSRF token first, then validates input, then acts, and show it returning 403 for a forged request, 422 for bad input, and success for a valid one.