38 lines
1.3 KiB
PHP
38 lines
1.3 KiB
PHP
<?php
|
|
// Protezione CSRF e sessione condivisa, compatibile PHP 7.0+.
|
|
function csrf_start_session() {
|
|
if (session_status() !== PHP_SESSION_ACTIVE) {
|
|
$secure = (!empty($_SERVER['HTTPS']) && $_SERVER['HTTPS'] !== 'off');
|
|
if (defined('PHP_VERSION_ID') && PHP_VERSION_ID >= 70300) {
|
|
session_set_cookie_params([
|
|
'lifetime' => 0,
|
|
'path' => '/',
|
|
'domain' => '',
|
|
'secure' => $secure,
|
|
'httponly' => true,
|
|
'samesite' => 'Strict',
|
|
]);
|
|
} else {
|
|
session_set_cookie_params(0, '/', '', $secure, true);
|
|
}
|
|
session_start();
|
|
}
|
|
if (empty($_SESSION['csrf_token'])) {
|
|
$_SESSION['csrf_token'] = bin2hex(random_bytes(32));
|
|
}
|
|
}
|
|
function csrf_token() { csrf_start_session(); return $_SESSION['csrf_token']; }
|
|
function csrf_field() {
|
|
echo '<input type="hidden" name="csrf_token" value="' . htmlspecialchars(csrf_token(), ENT_QUOTES, 'UTF-8') . '">';
|
|
}
|
|
function csrf_validate() {
|
|
csrf_start_session();
|
|
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
|
|
$token = $_POST['csrf_token'] ?? '';
|
|
if ($token === '' || !hash_equals($_SESSION['csrf_token'], $token)) {
|
|
http_response_code(400);
|
|
die('Invalid CSRF token.');
|
|
}
|
|
}
|
|
}
|
|
?>
|