Why this matters
CSRF tokens prevent malicious sites from forging form submissions on behalf of authenticated users. Without this protection, a user could unintentionally trigger unwanted actions by visiting a malicious page.
Implement anti‐CSRF tokens in forms performing sensitive actions (like state changes or deletions). Generate a unique token per session or request and validate it on the server before processing the form action.
CSRF tokens prevent malicious sites from forging form submissions on behalf of authenticated users. Without this protection, a user could unintentionally trigger unwanted actions by visiting a malicious page.
Side-by-side examples engineers can pattern-match during review.
<?php
// No CSRF token used
if ($_POST['acao'] === 'delete') {
deleteUser($_POST['id']);
}
?><?php
// Generate CSRF token
$_SESSION['csrf_token'] = bin2hex(random_bytes(32));
?>
<form method="POST">
<input type="hidden" name="csrf_token" value="<?= $_SESSION['csrf_token'] ?>">
<!-- other fields -->
</form>
<?php
// Validate CSRF token on submit
if (!isset($_POST['csrf_token']) || $_POST['csrf_token'] !== $_SESSION['csrf_token']) {
die('Invalid CSRF token');
}
if ($_POST['acao'] === 'delete') {
deleteUser($_POST['id']);
}
?><?php
// No CSRF token used
if ($_POST['acao'] === 'delete') {
deleteUser($_POST['id']);
}
?><?php
// Generate CSRF token
$_SESSION['csrf_token'] = bin2hex(random_bytes(32));
?>
<form method="POST">
<input type="hidden" name="csrf_token" value="<?= $_SESSION['csrf_token'] ?>">
<!-- other fields -->
</form>
<?php
// Validate CSRF token on submit
if (!isset($_POST['csrf_token']) || $_POST['csrf_token'] !== $_SESSION['csrf_token']) {
die('Invalid CSRF token');
}
if ($_POST['acao'] === 'delete') {
deleteUser($_POST['id']);
}
?>From the same buckets as this rule.