CSRF token for forms
Create a token per session, put it in every form and check it with hash_equals().
PHP · CSRF token for formsIntermediate
// create (once per session)
if (empty($_SESSION['csrf'])) {
$_SESSION['csrf'] = bin2hex(random_bytes(32));
}
// in the form
echo '<input type="hidden" name="_csrf" value="' . $_SESSION['csrf'] . '">';
// on submit
if (!hash_equals($_SESSION['csrf'] ?? '', $_POST['_csrf'] ?? '')) {
http_response_code(403);
exit('Invalid request.');
}csrfformssecurity