Skip to content
Tutorials Center
My learning

Topics

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.

PHP
$_SESSION['csrf'] ??= bin2hex(random_bytes(32));

Try it

PHP Create and check tokens

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.

PHP Simulating a protected POST request

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 with hash_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; Strict blocks it on all cross-site requests. Set it with session_set_cookie_params(['samesite' => 'Lax', 'secure' => true, 'httponly' => true]) before session_start(), or via setcookie() 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 Origin or Referer header 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.

PHP
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.