<?php
//Length in bytes of the CSRF token. It's converted to a hex string so the length will double.
define("CSRF_TOKEN_SIZE",10);
//Creates or evaulates a CSRF token.
function csrf_token($value=null){
//Ensure a token is here
if(!isset($_SESSION["_csrf"])){
$_SESSION["_csrf"]=$token=bin2hex(random_bytes(CSRF_TOKEN_SIZE));
}
else{
$token=$_SESSION["_csrf"];
}
//If no value is provided, return the current token
if($value===null){
return $token;
}
else{
//Check token
return $value===$token;
}
}
//Set a specific CSRF token
function csrf_set($token){
return $_SESSION["_csrf"]=$token;
}
//unsets the CSRF token
function csrf_unset(){
unset($_SESSION["_csrf"]);
}
//Check if the submitted CSRF token is valid
function csrf_check(){
return isset($_POST["_csrf"]) && csrf_token($_POST["_csrf"]);
}
//Generates the CSRF token field.
function csrf_field(){
return "<input type=\"hidden\" name=\"_csrf\" value=\"".csrf_token()."\" />";
}
?>
Comments
0 B
|👍
/👎