Initial commit
This commit is contained in:
23
includes/csrf.php
Normal file
23
includes/csrf.php
Normal file
@@ -0,0 +1,23 @@
|
||||
<?php
|
||||
declare(strict_types=1);
|
||||
|
||||
function csrf_token(): string {
|
||||
if (empty($_SESSION['_csrf'])) {
|
||||
$_SESSION['_csrf'] = bin2hex(random_bytes(32));
|
||||
}
|
||||
return (string)$_SESSION['_csrf'];
|
||||
}
|
||||
|
||||
function csrf_field(): string {
|
||||
$t = htmlspecialchars(csrf_token(), ENT_QUOTES, 'UTF-8');
|
||||
return '<input type="hidden" name="csrf" value="'.$t.'">';
|
||||
}
|
||||
|
||||
/**
|
||||
* Validate a CSRF token (uses provided token or POST body if omitted).
|
||||
*/
|
||||
function csrf_check(?string $token = null): bool {
|
||||
$sent = $token ?? (string)($_POST['csrf'] ?? '');
|
||||
$stored = (string)($_SESSION['_csrf'] ?? ($_SESSION['csrf'] ?? ''));
|
||||
return ($sent !== '' && $stored !== '' && hash_equals($stored, $sent));
|
||||
}
|
||||
Reference in New Issue
Block a user