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.
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.
// 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
Use hash_equals() for token comparison — it is timing-attack resistant unlike ===.