Content · Web Development · PHP

Implementing CSRF Protection in PHP

Bind state-changing form submissions to a random token held in the server session and compared in constant.

1 views Published Oct 17, 2026 Updated Oct 17, 2026 admin

Bind state-changing form submissions to a random token held in the server session and compared in constant time.

The examples introduce the underlying control before showing a verification and an application-level safeguard.

What You Will Build


Bind state-changing form submissions to a random token held in the server session and compared in constant time.

Prerequisites


Use PHP 8.4 or newer, HTTPS for all authentication operations, and an application session or database where required. Example configuration values are placeholders, never production secrets.

Example 1: Basic Operation


Render a random synchronizer token inside a state-changing form.

<?php
session_start();
$_SESSION['csrf'] ??= bin2hex(random_bytes(32));
echo '<input type="hidden" name="csrf" value="' . htmlspecialchars($_SESSION['csrf'], ENT_QUOTES, 'UTF-8') . '">';

Example 2: A Different Use Case


Reject absent and mismatched POST tokens before changing state.

<?php
session_start();
$expected = $_SESSION['csrf'] ?? '';
$received = $_POST['csrf'] ?? '';
if (!is_string($received) || !is_string($expected) || $expected === '' || !hash_equals($expected, $received)) {
    http_response_code(403); exit('Request rejected');
}
// The validated POST request may now reach the application handler.

Practical Example: Checking the Result


Layer token checks with the HTTP method and authenticated session.

<?php
session_start();
if ($_SERVER['REQUEST_METHOD'] !== 'POST') { http_response_code(405); exit; }
$token = $_POST['csrf'] ?? null;
if (!is_string($token) || empty($_SESSION['csrf']) || !hash_equals($_SESSION['csrf'], $token)) {
    http_response_code(403); exit;
}
// Keep an authenticated session and server-side authorization checks.

Important Behavior and Edge Cases


CSRF tokens are not a substitute for session cookies with SameSite settings, and tokens must not be placed in URLs or logs.

Enforce controls on the server, test denial paths and do not assume that a snippet alone implements an entire production workflow.

Comparison with Related Functions


ApproachKey distinction
Implementing CSRF Protection in PHPBind state-changing form submissions to a random token held in the server session and compared in constant time.
Related techniqueUse CSRF checks on POST/PUT/PATCH/DELETE; safe GET routes must not mutate server state.

Common Beginner Mistakes


MistakeCorrect approach
Confusing this operation with a neighboring cryptographic or security mechanismUse CSRF checks on POST/PUT/PATCH/DELETE; safe GET routes must not mutate server state.
Ignoring a security prerequisite or failure caseCSRF tokens are not a substitute for session cookies with SameSite settings, and tokens must not be placed in URLs or logs.

Key Takeaways


  • Bind state-changing form submissions to a random token held in the server session and compared in constant time.
  • CSRF tokens are not a substitute for session cookies with SameSite settings, and tokens must not be placed in URLs or logs.
  • Use CSRF checks on POST/PUT/PATCH/DELETE; safe GET routes must not mutate server state.

Apply this behavior to a real application only after confirming the required extension, configuration and failure handling on the deployment runtime.

Share this resourceSend this page to someone who may find it useful.