PHP
Public
CSRF Token Input
A simple PHP pattern for rendering and validating a CSRF token.
#php
#csrf
#security
#form
PHP
<?php
session_start();
if (empty($_SESSION['csrf_token'])) {
$_SESSION['csrf_token'] = bin2hex(random_bytes(32));
}
function csrfInput(): string
{
$token = htmlspecialchars($_SESSION['csrf_token'], ENT_QUOTES, 'UTF-8');
return '<input type="hidden" name="csrf_token" value="' . $token . '">';
}
function isValidCsrfToken(string $token): bool
{
return hash_equals($_SESSION['csrf_token'] ?? '', $token);
}
Notes
Use CSRF protection on forms that change data.