📡 You're offline — showing cached content
New version available!
Quick Access
Tutorials PHP for Beginners CSRF Protection

CSRF Protection

5 min read Quiz at the end
CSRF attacks trick logged-in users into submitting forms without their knowledge. Add a unique secret token to every form, store it in the session, and verify it on every POST request before processing.

CSRF Protection

Cross-Site Request Forgery prevention using tokens.

// Generate token and store in session
function generateCsrfToken(): string {
    if (empty($_SESSION["csrf_token"])) {
        $_SESSION["csrf_token"] = bin2hex(random_bytes(32));
    }
    return $_SESSION["csrf_token"];
}

// Validate submitted token
function validateCsrfToken(string $token): bool {
    return isset($_SESSION["csrf_token"])
        && hash_equals($_SESSION["csrf_token"], $token);
}

// In your form:
// <input type="hidden" name="csrf" value="<?= generateCsrfToken() ?>">

// In your form handler:
session_start();
if (!validateCsrfToken($_POST["csrf"] ?? "")) {
    http_response_code(403);
    die("CSRF token mismatch");
}
Topic Quiz · 5 questions

Test your understanding before moving on

1. What does CSRF stand for?
💡 CSRF is Cross-Site Request Forgery — tricking a user into making unintended requests.
2. How do CSRF tokens protect forms?
💡 The token is unique per session — an attacker cannot guess it from another site.
3. Which function generates cryptographically secure random bytes?
💡 random_bytes($length) generates cryptographically secure random bytes.
4. Why use hash_equals() to compare CSRF tokens?
💡 hash_equals() is timing-attack-safe — regular === comparison leaks info through timing.
5. When should the CSRF token be regenerated?
💡 Regenerate the CSRF token after each form submission to prevent reuse.