SyntaxStudy
Sign Up
PHP Intermediate 4 min read

CSRF Protection

CSRF

CSRF tricks a logged-in user into submitting a forged request. Defend with a per-session token included in every state-changing form or AJAX request.

Example
// Generate and store token
$_SESSION["csrf"] = bin2hex(random_bytes(32));
// In form
echo "<input type=\"hidden\" name=\"csrf\" value=\"{$_SESSION["csrf"]}\">";
// Verify on submit
if (!hash_equals($_SESSION["csrf"], $_POST["csrf"] ?? "")) {
    http_response_code(403); exit("CSRF check failed");
}
// Laravel: @csrf in Blade forms — handled automatically
Pro Tip

Use hash_equals() for token comparison — it is timing-attack resistant unlike ===.