Skip to main content

Lesson 3 of 7

CSRF - Cross-Site Request Forgery Prevention

CSRF tricks a logged-in user's browser into making an unintended request to your application. A malicious site hosts an invisible form pointing to yoursite.com/delete-account - when the victim (already logged in) visits, their browser sends the request with their session cookie. The fix: synchroniser tokens that the attacker's site cannot read.

12 minBy Priygop Editorial TeamUpdated 2026Peer Reviewed & Verified

CSRF Token Implementation

CSRF Token Implementation
<?php
declare(strict_types=1);

// ── CSRF attack scenario ───────────────────────────────────────
// 1. Alice is logged in to blog.com
// 2. Alice visits evil.com (malicious link in email)
// 3. evil.com's page contains:
//    <img src="https://blog.com/posts/42/delete">
//    or <form action="https://blog.com/posts/42/delete" method="POST">
//    with auto-submit JS
// 4. Alice's browser sends the GET/POST WITH her session cookie
// 5. blog.com thinks Alice intentionally deleted post 42

// ── CSRF Token generation ─────────────────────────────────────
class CsrfToken {
    private const SESSION_KEY = "_csrf_token";

    public static function generate(): string {
        if (empty($_SESSION[self::SESSION_KEY])) {
            $_SESSION[self::SESSION_KEY] = bin2hex(random_bytes(32));
        }
        return $_SESSION[self::SESSION_KEY];
    }

    public static function validate(string $token): bool {
        $sessionToken = $_SESSION[self::SESSION_KEY] ?? "";
        if (empty($sessionToken) || empty($token)) return false;

        // hash_equals - constant-time comparison (timing attack prevention)
        return hash_equals($sessionToken, $token);
    }

    public static function regenerate(): void {
        $_SESSION[self::SESSION_KEY] = bin2hex(random_bytes(32));
    }

    public static function field(): string {
        return '<input type="hidden" name="_csrf_token" value="' . self::generate() . '">';
    }
}

// ── Include in every state-changing form ──────────────────────
// In the HTML form:
?>
<form method="POST" action="/posts/create">
    <?= CsrfToken::field() ?>
    <input type="text" name="title">
    <button type="submit">Create</button>
</form>
<?php

// ── Validate on every POST handler ────────────────────────────
function validateCsrf(): void {
    if ($_SERVER["REQUEST_METHOD"] !== "POST") return;

    $token = $_POST["_csrf_token"] ?? "";
    if (!CsrfToken::validate($token)) {
        // Log attempted CSRF for security monitoring
        error_log("CSRF validation failed. IP: " . ($_SERVER["REMOTE_ADDR"] ?? "unknown"));
        http_response_code(403);
        die("Session expired or invalid request. Please go back and try again.");
    }
    // Regenerate after successful validation (double-submit protection)
    CsrfToken::regenerate();
}

// ── For AJAX requests - send token in header ──────────────────
// JavaScript: include CSRF token in X-CSRF-Token header
// PHP: verify the header
function validateAjaxCsrf(): void {
    $token = $_SERVER["HTTP_X_CSRF_TOKEN"] ?? "";
    if (!CsrfToken::validate($token)) {
        http_response_code(403);
        header("Content-Type: application/json");
        die(json_encode(["error" => "CSRF validation failed"]));
    }
}

Quick Quiz

Tip

Tip

Practice CSRF CrossSite Request Forgery Prevention in small, isolated examples before integrating into larger projects. Breaking concepts into small experiments builds genuine understanding faster than reading alone.

Diagram
Loading diagram…

Visual architecture and concepts for CSRF - Cross-Site Request Forgery Prevention

Practice Task

Note

Practice Task - (1) Write a working example of CSRF CrossSite Request Forgery Prevention from scratch without looking at notes. (2) Modify it to handle an edge case (empty input, null value, or error state). (3) Share your solution in the Priygop community for feedback.

Common Mistake

Warning

A common mistake with CSRF CrossSite Request Forgery Prevention is skipping edge case testing - empty inputs, null values, and unexpected data types. Always validate boundary conditions to write robust, production-ready php code.

Hands-on Practice Tools for this Course

Test what you learn using these free in-browser developer utilities (no signup required).

All 40+ Tools

Topics in This Module

0/7 done