Skip to content
Tutorials Center
My learning

Topics

Lesson 97 of 147 ยท Security

Preventing CSRF

Learn how cross-site request forgery works and how to stop it in PHP - random tokens with random_bytes, hash_equals checks, SameSite cookies and Origin headers.

Cross-site request forgery (CSRF, sometimes said "sea-surf") tricks a logged-in user's browser into sending a request to your site that the user never meant to send. The attacker doesn't steal the session or see your pages. They don't need to: browsers attach cookies to requests automatically, so a form on evil.example that posts to bank.example/transfer arrives at your server with the victim's session cookie. To your PHP code, it looks exactly like the user clicked "Transfer".

The classic defense is a CSRF token: a secret random value that your site puts into its own forms and checks on every state-changing request. A foreign site can't read your pages, so it can't know the token. Modern browsers add two more layers, SameSite cookies and the Origin and Sec-Fetch-Site headers. This lesson builds all three in plain PHP.

You should know how sessions and cookies work. Our editor has no web server, so the request examples are simulations: they fill $_POST, $_SERVER and a session array by hand, then call the handler.

How a CSRF attack works

Imagine a site where logged-in users can change their email address with a POST to /account/email. The handler checks that the user is logged in, and that's all. Here is the attack, played out step by step:

PHP A forged request succeeds

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.

The form submits itself the moment the page loads; the victim may see nothing but a flash. Now the attacker can use "forgot password" to take over the account. Notice what the attacker didn't need: the password, the session ID, or any way to read the response. CSRF is a write-only attack, which is why it targets actions: changing settings, transferring money, deleting data, posting messages.

Two rules come straight out of this:

  • GET requests must never change anything. An <img src="https://shop.example/logout"> or a link triggers a GET without any form at all. Use POST (or PUT, PATCH, DELETE) for actions, and protect those.
  • Being logged in proves nothing about intent. The cookie only shows which browser sent the request, not which page it came from.

The synchronizer token pattern

The fix is to require a value the attacker can't know. When the session starts, generate a random token, store it in the session, and print it into every form as a hidden field. When a POST arrives, compare the submitted token with the one in the session. The evil site can make the browser send a request, but it can't read your page (the browser's same-origin policy forbids that), so it can't put the correct token into its forged form.

The token must be unpredictable, so it comes from random_bytes(), PHP's cryptographically secure random generator. Thirty-two bytes, shown as 64 hex characters with bin2hex(), is plenty:

PHP Generating a token and adding it to a form

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.

The token is different on every run but stays the same for the whole session, so the user can open several tabs and submit any of them. On a real server, $session is $_SESSION after session_start(). Never use rand(), mt_rand(), uniqid() or md5(time()) for tokens; their output can be predicted. The Cryptography lesson explains why.

Checking the token with hash_equals

On every POST, compare the submitted token with the session's token. Three details matter:

  1. Reject missing tokens. If the session has no token yet, or the form sent none, the request fails.
  2. Check the type. $_POST['_token'] can be an array if the attacker sends _token[]=x. Passing an array to a string function throws a TypeError.
  3. Compare with hash_equals(), not ===. A normal string comparison stops at the first different character, so it takes slightly longer the more leading characters match. In theory, an attacker who measures response times precisely could guess a secret character by character. hash_equals() always takes the same time for strings of the same length. It's the standard choice whenever you compare a secret with user input.
PHP Verifying the token

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.

Only the request from our own form passes. In a real application, run this check in one central place, before any POST, PUT, PATCH or DELETE handler (a front controller or middleware, as in Front Controllers and Routing), so nobody can forget it on a new form.

Practical details

  • AJAX and JSON APIs: put the token in a <meta name="csrf-token"> tag and send it in a request header such as X-CSRF-Token. Read it from $_SERVER['HTTP_X_CSRF_TOKEN']. A cross-site form can't set custom headers, and a cross-site fetch() with custom headers needs your permission through CORS.
  • Rotate the token on login and logout, together with session_regenerate_id(true). That also prevents login CSRF, where the attacker logs the victim into the attacker's account so the victim's later activity lands there.
  • Per-session or per-form? One token per session is the common choice and works with multiple tabs and the back button. Single-use tokens per form add little against CSRF and cause "token expired" errors for real users.
  • Don't put tokens in URLs. URLs end up in logs, browser history and Referer headers.

SameSite cookies

Browsers now let a site say when its cookies may travel with cross-site requests. The SameSite cookie attribute has three values:

Value Cookie sent on cross-site requests? Typical use
Strict Never. Even following a link from another site arrives without it Highly sensitive sites; users appear logged out after clicking an external link
Lax Only on top-level navigations with safe methods (clicking a link, a GET form) The sensible default for session cookies
None Always (requires Secure) Embedded widgets, third-party integrations

With Lax, the forged POST from the first example arrives without the session cookie, so PHP sees an anonymous visitor and the attack fails. You set the attribute with the options array of setcookie() (PHP 7.3+), or for the session cookie with session_set_cookie_params() or session.cookie_samesite in php.ini:

PHP
<?php
session_set_cookie_params([
    'lifetime' => 0,
    'path' => '/',
    'secure' => true,      // only over HTTPS
    'httponly' => true,    // not readable from JavaScript
    'samesite' => 'Lax',
]);
session_start();

setcookie('theme', 'dark', [
    'expires' => time() + 60 * 60 * 24 * 365,
    'path' => '/',
    'secure' => true,
    'httponly' => true,
    'samesite' => 'Lax',
]);

The rules a browser applies are easy to model. This function decides whether a cookie is attached to a request, following the table above:

PHP Which requests carry a SameSite cookie?

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.

Under Lax, only the plain link sends the cookie, and that's harmless as long as GET requests never change anything. The model is simplified (real browsers have a few more rules, for example around redirects and <iframe>s), but it captures the behavior that matters for CSRF.

SameSite is a strong second layer, not a replacement for tokens. "Same site" means the same registrable domain, so blog.example.com counts as the same site as shop.example.com: an attacker who controls any subdomain can bypass it. Older browsers ignore the attribute, and Chrome's habit of treating cookies without SameSite as Lax isn't shared by every browser. Set the attribute explicitly and use tokens.

Checking Origin and Sec-Fetch-Site

Browsers also tell you where a request came from. On cross-origin POST requests they send an Origin header (Origin: https://evil.example), and all current browsers send Fetch Metadata headers such as Sec-Fetch-Site, with the value same-origin, same-site, cross-site or none (typed into the address bar). Websites can't forge these headers from a victim's browser, so rejecting cross-site writes is a cheap extra layer:

PHP Rejecting cross-site writes by header

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.

Unlike SameSite, this check also rejects the subdomain, because it only accepts same-origin. The curl request is allowed: scripts send whatever headers they like, but they also don't carry a victim's cookies, so CSRF isn't the concern there (authentication is). If your site legitimately receives cross-site POSTs, such as payment provider callbacks, exempt those specific routes and authenticate them with a signature instead (see hash_hmac() in Cryptography).

Putting it together

A solid CSRF defense for a PHP application has these parts:

  1. Actions use POST, PUT, PATCH or DELETE; GET never changes state.
  2. Session cookies are set with SameSite=Lax, Secure and HttpOnly.
  3. Every unsafe request is checked centrally for a valid token, compared with hash_equals().
  4. Optionally, cross-site writes are rejected early using Sec-Fetch-Site or Origin.
  5. The token and session ID are rotated on login and logout.

Frameworks do all of this for you: Laravel's @csrf directive and VerifyCsrfToken/ValidateCsrfToken middleware, and Symfony's CSRF component. Knowing how it works lets you spot the gaps: an endpoint excluded "temporarily", a GET route that deletes things, or an XSS hole. XSS defeats every CSRF defense, because a script running on your own page can read the token. That's one more reason to take Preventing XSS seriously.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. Why does a forged form on evil.example work against a site with no CSRF protection?

    The browser sends the session cookie with the forged request, so the server treats it as coming from the logged-in user.
  2. 2. Which is the right way to create a CSRF token?

    random_bytes() is cryptographically secure. Time-based and mt_rand values can be predicted.
  3. 3. Why compare tokens with hash_equals() instead of ===?

    A normal comparison returns as soon as a character differs. hash_equals() is a constant-time comparison for secrets.
  4. 4. The session cookie has SameSite=Lax. Which cross-site request still carries it?

    Lax cookies are sent only on top-level navigations with safe methods such as GET. That's why GET requests must never change state.
  5. 5. An attacker finds an XSS hole on your site. What happens to your CSRF tokens?

    Same-origin scripts can read your pages, including hidden token fields. Preventing XSS is a precondition for CSRF protection.

Summary

  • CSRF makes a logged-in user's browser send a request they didn't intend; it works because browsers attach cookies automatically. It targets actions, not data theft.
  • GET must never change state. Protect every POST, PUT, PATCH and DELETE.
  • The synchronizer token: bin2hex(random_bytes(32)) stored in the session, printed as a hidden field (or a meta tag and request header for AJAX), and checked on every unsafe request.
  • Validate the token's type and compare with hash_equals(), a constant-time comparison, in one central place.
  • Set session cookies with SameSite=Lax, Secure and HttpOnly. SameSite is a strong extra layer but treats subdomains as the same site.
  • Sec-Fetch-Site and Origin headers let you reject cross-site writes cheaply.
  • Rotate the token and session ID on login and logout, and fix XSS first: it defeats every CSRF defense.

Next: Password Hashing