PHP Reference ยท Web and Security
CSRF protection in PHP
Understand cross-site request forgery in PHP and prevent it with per-session tokens, hash_equals() checks, SameSite cookies and safe request methods.
Cross-site request forgery (CSRF) tricks a logged-in user's browser into sending a request they did not intend. Browsers attach cookies automatically, so a hidden form on another website that posts to https://your-bank.example/transfer arrives with the user's real session cookie, and the server cannot tell it from a genuine click.
The classic defense is a CSRF token: a random value stored in the session and also placed in every form. A forged request cannot know the token, so the server rejects it. Modern defense in depth adds SameSite cookies and keeps state-changing actions off GET requests.
$_SESSION['csrf'] ??= bin2hex(random_bytes(32));
Try it
Press Run (or Ctrl + Enter) to see the result here.
Program input ยท what you'd type while the program runs
Type the answers before you press Run, one per line. Each time the program reads a line (with fgets(STDIN)), it gets the next line from this box.
Press Run (or Ctrl + Enter) to see the result here.
Program input ยท what you'd type while the program runs
Type the answers before you press Run, one per line. Each time the program reads a line (with fgets(STDIN)), it gets the next line from this box.
How the defense works
- Token per session (the synchronizer pattern): generate with
random_bytes(), keep it in$_SESSION, put it in a hidden field of every state-changing form, and compare on the server withhash_equals(). - SameSite cookies tell the browser when to withhold a cookie on cross-site requests.
SameSite=Lax(the default in modern browsers) blocks the cookie on cross-site POSTs;Strictblocks it on all cross-site requests. Set it withsession_set_cookie_params(['samesite' => 'Lax', 'secure' => true, 'httponly' => true])beforesession_start(), or viasetcookie()options. - Safe methods stay safe. GET, HEAD and OPTIONS must never change data. Use POST, PUT, PATCH or DELETE for changes, and check the token on all of them.
- Origin check. Comparing the
OriginorRefererheader with your own host is a cheap extra layer, but not a replacement for tokens.
Read-only: setting the cookie flags in a real request.
session_set_cookie_params([ 'lifetime' => 0, 'path' => '/', 'secure' => true, 'httponly' => true, 'samesite' => 'Lax', ]); session_start();
Usage notes
- Tokens must be unpredictable. Never use
uniqid(),time(),md5(rand())or the session id itself. - Compare in constant time with
hash_equals(), and always reject a missing token. - Rotate after login (regenerate the session id and token) to prevent fixation.
- Per-form tokens are optional. One token per session is enough for most sites. Per-request tokens add complexity and break the Back button.
- JSON APIs that use cookie authentication need CSRF protection too. APIs that authenticate with a bearer header, not a cookie, are not vulnerable.
- XSS defeats CSRF tokens: a script on your page can read the token. Escape output as described in XSS prevention.
- Frameworks (Laravel, Symfony) generate and verify tokens automatically; keep that middleware on.
Related
- Sessions,
setcookie(), XSS prevention,hash_equals() - Lessons: CSRF, Sessions, Security basics