WebOrbiton
v1.0.0.0

StocketBase

26 lines · 618 B
  1. <?php
  2. ​
  3. declare(strict_types=1);
  4. ​
  5. final class Csrf
  6. {
  7. public static function token(): string
  8. {
  9. if (empty($_SESSION['csrf_token'])) {
  10. $_SESSION['csrf_token'] = bin2hex(random_bytes(32));
  11. }
  12. ​
  13. return $_SESSION['csrf_token'];
  14. }
  15. ​
  16. public static function field(): string
  17. {
  18. return '<input type="hidden" name="csrf_token" value="' . htmlspecialchars(self::token()) . '">';
  19. }
  20. ​
  21. public static function verify(?string $token): bool
  22. {
  23. return is_string($token) && isset($_SESSION['csrf_token']) && hash_equals($_SESSION['csrf_token'], $token);
  24. }
  25. }
  26. ​