AJAX Security

AJAX Security: CSRF Protection for Fetch Requests

Protect cookie-authenticated AJAX requests against cross-site request forgery with server-validated tokens.

AJAX Security: CSRF Protection for Fetch Requests

Cross-site request forgery (CSRF) tricks a browser into sending an authenticated request to a site where the user is signed in. State-changing endpoints should verify a CSRF token in addition to authentication and authorization.

Generate a session token in PHP

if (empty($_SESSION['csrf_token'])) {
    $_SESSION['csrf_token'] = bin2hex(random_bytes(32));
}

Expose the token to the page through a safely escaped meta element or form field. Send it in a custom request header:

await fetch('/api/update.php', {
  method: 'POST',
  headers: { 'X-CSRF-Token': csrfToken },
  body: new FormData(form)
});

Verify on the server

Compare the submitted token with the session token using hash_equals(). Reject missing or invalid tokens. Use secure cookie settings and SameSite as defense in depth, not as a replacement for a complete CSRF strategy.

Share this page Help other developers discover this resource.