|
<?php |
|
// At top level file you must place token generation and check logic |
|
|
|
//It should be bellow the session start |
|
@session_start(); |
|
|
|
|
|
// We must have a Constant to control it, to disable if need (and must not be, but just in case) |
|
defined('DISABLE_CROSS_PROTECTION') or define('DISABLE_CROSS_PROTECTION', false); |
|
|
|
// The token can be anything, in this case, just a really random id |
|
//Create/Get the Token |
|
function genToken($force = false){ |
|
//To increase security a random key is generated every time |
|
$key = getTokenKey($force); |
|
//Sent $force = true if want to force renew the token. |
|
if($force || (!array_key_exists($key,$_SESSION ) || !$_SESSION[$key])){ |
|
$_SESSION[$key] = genHash(); |
|
} |
|
return $_SESSION[$key]; |
|
} |
|
|
|
function getTokenKey($force = false){ |
|
//Sent $force = true if want to force renew the token. |
|
if($force || (!array_key_exists('csrf_token_key_name',$_SESSION ) || !$_SESSION['csrf_token_key_name'])){ |
|
$_SESSION['csrf_token_key_name'] = genHash(); |
|
} |
|
return $_SESSION['csrf_token_key_name']; |
|
} |
|
|
|
function genHash(){ |
|
return md5(uniqid(mt_rand(), true)."SALT"); |
|
} |
|
|
|
|
|
// This is the process to check the token |
|
function checkToken(){ |
|
$key = getTokenKey($force); |
|
|
|
//Safe retrive token from the input: |
|
$token = filter_input(INPUT_POST, $key, FILTER_SANITIZE_STRING); |
|
|
|
$currentToken = $_SESSION[$key]; |
|
genToken(true); |
|
if (!$token || $token !== $currentToken) { |
|
// return 405 http status code, default error response for this case, but you can customize anyway. |
|
header($_SERVER['SERVER_PROTOCOL'] . ' 405 Method Not Allowed'); |
|
exit; |
|
} |
|
} |
|
|
|
// We only check this for POST method, if you are using GET to "create/update" data its wrong and must be fixed |
|
// Also, in some cases people uses PUT and PATCH in those cases it must be fixed as weel. |
|
if ($_SERVER['REQUEST_METHOD'] === 'POST' && !DISABLE_CROSS_PROTECTION) { |
|
checkToken(); |
|
} |