CSRF Protection
On this page
What CSRF Is
CSRF tricks a logged-in user’s browser into sending a state-changing request (POST/DELETE) without the user intending it. Because cookies are sent automatically, the server may accept the action unless you add protection.
CSRF Token Strategy
Generate a random token server-side, store it in the session, and include it in forms. On POST, verify it.
Generate Token
<?php
session_start();
if (!isset($_SESSION["csrf_token"])) {
$_SESSION["csrf_token"] = bin2hex(random_bytes(32));
}
$token = $_SESSION["csrf_token"];
Add Token to Form
<form method="POST" action="/save.php"> <input type="hidden" name="csrf_token" value="<?php echo htmlspecialchars($token, ENT_QUOTES, "UTF-8"); ?>"> <input name="title"> <button type="submit">Save</button> </form>
Verify Token on POST
<?php
session_start();
$sent = $_POST["csrf_token"] ?? "";
$expected = $_SESSION["csrf_token"] ?? "";
if (!hash_equals($expected, $sent)) {
http_response_code(403);
echo "Forbidden";
exit;
}
SameSite Is Helpful but Not Enough
SameSite cookies reduce CSRF risk, but token validation remains the most reliable defense—especially for complex flows, older browsers, and edge cases.
Production Tip
Use CSRF tokens for all state-changing requests. Rotate tokens per session (and optionally per form). Combine with SameSite cookies and proper origin checks for APIs when applicable.