| 1234567891011121314151617181920212223242526272829303132333435 |
- <?php
- /**
- * CSRF protection for all admin POST requests.
- */
- declare(strict_types=1);
- function csrf_token(): string
- {
- session_boot();
- if (empty($_SESSION['csrf'])) {
- $_SESSION['csrf'] = bin2hex(random_bytes(32));
- }
- return $_SESSION['csrf'];
- }
- /** Hidden input for HTML forms. */
- function csrf_field(): string
- {
- return '<input type="hidden" name="_csrf" value="' . e(csrf_token()) . '">';
- }
- /**
- * Verify the token from a form field or the X-CSRF-Token header (API calls).
- * Ends the request on failure.
- */
- function csrf_verify(): void
- {
- session_boot();
- $sent = $_POST['_csrf'] ?? $_SERVER['HTTP_X_CSRF_TOKEN'] ?? '';
- if (empty($_SESSION['csrf']) || !hash_equals($_SESSION['csrf'], (string)$sent)) {
- http_response_code(419);
- exit('Invalid or missing CSRF token. Go back, reload the page and try again.');
- }
- }
|