CSRF Protection in PHP

Cross-Site Request Forgery (CSRF) tricks a user into submitting a request they didn’t intend. Protecting your forms against this attack is simple if you generate and verify tokens properly.

1. Generating a token

Create a random token, store it in the session, and embed it into your form as a hidden input. Never reuse the same token across multiple requests.

if (!isset($_SESSION['csrf_token'])) { $_SESSION['csrf_token'] = bin2hex(random_bytes(32)); } // in your form echo '';

2. Verifying the token

When processing the request, compare the submitted token to the one in the session. If they differ or are missing, deny the request.

if ($_SERVER['REQUEST_METHOD'] === 'POST') { $submitted = $_POST['csrf'] ?? ''; if (!hash_equals($_SESSION['csrf_token'], $submitted)) { header('HTTP/1.1 403 Forbidden'); exit('Invalid CSRF token'); } // process form }

3. Rotate tokens

After a successful submission, rotate the token so an attacker can’t replay it. This limits the lifetime of any leaked tokens.