PHP Code Examples

Protect PHP Forms with a CSRF Token

Use a session-backed token to help prevent cross-site request forgery on state-changing form submissions.

Generate a token

<?php
session_start();

if (empty($_SESSION['csrf_token'])) {
    $_SESSION['csrf_token'] = bin2hex(random_bytes(32));
}

Include it in the form

<input
    type="hidden"
    name="csrf_token"
    value="<?= htmlspecialchars($_SESSION['csrf_token'], ENT_QUOTES, 'UTF-8') ?>"
>

Validate on submission

<?php
session_start();

$submitted = $_POST['csrf_token'] ?? '';
$stored = $_SESSION['csrf_token'] ?? '';

if (!is_string($submitted) ||
    !is_string($stored) ||
    $stored === '' ||
    !hash_equals($stored, $submitted)) {
    http_response_code(403);
    exit('Invalid request token.');
}

Important

Use CSRF protection for state-changing actions, including account changes and administrative operations. SameSite cookies are useful defense-in-depth, not a universal replacement for tokens.

Share this page Help other developers discover this resource.