41 lines
1.1 KiB
PHP
41 lines
1.1 KiB
PHP
<?php
|
|
if (session_status() === PHP_SESSION_NONE) {
|
|
session_start();
|
|
}
|
|
|
|
/**
|
|
* Generates a CSRF token and stores it in the session.
|
|
* @return string The generated token.
|
|
*/
|
|
function generate_csrf_token() {
|
|
if (empty($_SESSION['csrf_token'])) {
|
|
$_SESSION['csrf_token'] = bin2hex(random_bytes(32));
|
|
}
|
|
return $_SESSION['csrf_token'];
|
|
}
|
|
|
|
/**
|
|
* Validates the submitted CSRF token.
|
|
* @return bool True if the token is valid, false otherwise.
|
|
*/
|
|
function validate_csrf_token() {
|
|
if (!isset($_POST['csrf_token']) || !isset($_SESSION['csrf_token'])) {
|
|
return false;
|
|
}
|
|
if (!hash_equals($_SESSION['csrf_token'], $_POST['csrf_token'])) {
|
|
return false;
|
|
}
|
|
// Invalidate the token after use to prevent replay attacks
|
|
unset($_SESSION['csrf_token']);
|
|
return true;
|
|
}
|
|
|
|
/**
|
|
* Returns the HTML hidden input field for the CSRF token.
|
|
* @return string The HTML input field.
|
|
*/
|
|
function csrf_input_field() {
|
|
$token = generate_csrf_token();
|
|
return '<input type="hidden" name="csrf_token" value="' . htmlspecialchars($token) . ''>';
|
|
}
|