Loading...
Searching...
No Matches
csrf_tokens.php
<?php
function updateCsrf() {
if(!sessionExists()) {
session_start();
}
$_SESSION['csrf_token'] = generateCsrf();
}
function sessionExists() {
if (version_compare(phpversion(), '5.4.0', '>')) {
return session_id() !== '';
} else {
return session_status() === PHP_SESSION_ACTIVE;
}
}
function generateCsrf() {
if (version_compare(phpversion(), '7.0.0', '>=')) {
$random = generateRandom();
if($random !== false) return $random;
}
if (function_exists('mcrypt_create_iv')) {
return generateMcrypt();
}
return generateOpenssl();
}
function generateRandom() {
try {
return bin2hex(random_bytes(32));
} catch (Exception $e) {
return false;
}
}
function generateMcrypt() {
return bin2hex(mcrypt_create_iv(32, MCRYPT_DEV_URANDOM));
}
function generateOpenssl() {
return bin2hex(openssl_random_pseudo_bytes(32));
}
function getCsrf() {
if(!sessionExists()) {
session_start();
}
if(!array_key_exists('csrf_token', $_SESSION)) {
updateCsrf();
}
return $_SESSION['csrf_token'];
}
function getCsrfField() {
return sprintf("<input type=\"hidden\" name=\"csrf_token\" value=\"%s\">", getCsrf());
}
function verifyCsrf($csrf_token) {
$current_csrf = getCsrf();
// Prefer hash_equals over === because the latter is vulnerable to timing attacks
if(function_exists('hash_equals')) {
return hash_equals($current_csrf, $csrf_token);
}
return $current_csrf === $csrf_token;
}
function verifyCsrfPost() {
return (isset($_POST['csrf_token']) && verifyCsrf($_POST['csrf_token']));
}