csrf.php 875 B

1234567891011121314151617181920212223242526272829303132333435
  1. <?php
  2. /**
  3. * CSRF protection for all admin POST requests.
  4. */
  5. declare(strict_types=1);
  6. function csrf_token(): string
  7. {
  8. session_boot();
  9. if (empty($_SESSION['csrf'])) {
  10. $_SESSION['csrf'] = bin2hex(random_bytes(32));
  11. }
  12. return $_SESSION['csrf'];
  13. }
  14. /** Hidden input for HTML forms. */
  15. function csrf_field(): string
  16. {
  17. return '<input type="hidden" name="_csrf" value="' . e(csrf_token()) . '">';
  18. }
  19. /**
  20. * Verify the token from a form field or the X-CSRF-Token header (API calls).
  21. * Ends the request on failure.
  22. */
  23. function csrf_verify(): void
  24. {
  25. session_boot();
  26. $sent = $_POST['_csrf'] ?? $_SERVER['HTTP_X_CSRF_TOKEN'] ?? '';
  27. if (empty($_SESSION['csrf']) || !hash_equals($_SESSION['csrf'], (string)$sent)) {
  28. http_response_code(419);
  29. exit('Invalid or missing CSRF token. Go back, reload the page and try again.');
  30. }
  31. }