Files
Rodrigo Cortés Cano 42fd9870d4 Improve invalid CSRF token response page (#1067)
Improve CSRF invalid error page

- Replaces the raw hardcoded error with localized PALANG text. 
- Provides a simple Continue link back to main.php

Related to the 4.0 branch fix in PR #1055.
2026-07-03 18:31:55 +01:00

46 lines
1.3 KiB
PHP

<?php
class CsrfToken
{
public static function generate(): string
{
if (!isset($_SESSION['CSRF_Tokens']) || !is_array($_SESSION['CSRF_Tokens'])) {
$_SESSION['CSRF_Tokens'] = [];
}
// remove any expired tokens
foreach ($_SESSION['CSRF_Tokens'] as $key => $value) {
if ($value < (time())) {
unset($_SESSION['CSRF_Tokens'][$key]);
}
}
$token = bin2hex(random_bytes(16));
$_SESSION['CSRF_Tokens'][$token] = (time() + 3600); // is an hour an acceptable expiry time?
return $token;
}
/**
* @param string $token
* @return bool
* @throws CsrfInvalidException
*/
public static function assertValid(string $token): bool
{
if (!isset($_SESSION['CSRF_Tokens']) || !is_array($_SESSION['CSRF_Tokens'])) {
$_SESSION['CSRF_Tokens'] = [];
}
$value = (int)($_SESSION['CSRF_Tokens'][$token] ?? 0);
// token can only be used once.
unset($_SESSION['CSRF_Tokens'][$token]);
// token cannot have expired
if ($value < time()) {
throw new CsrfInvalidException("Invalid CSRF token - try refreshing the page and try again?");
}
return true;
}
}