I am trying to build a CSRF protected web app in PHP. I am trying to keep a token in session for one time use for user as to protect their security. Now the problem is that when ever I refresh page or visit another page my token get changed. I don't want it to happen. I want to set single session token so user can access website without any problem of token mismatch. My codes for session are
<?php
function rand_csrf_string($length = 7) {
$characters = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ';
$randomString = '';
for ($i = 0; $i < $length; $i++) {
$randomString .= $characters[rand(0, strlen($characters) - 1)];
}
return $randomString;
}
if(!isset($_SESSION['CSRF_TOKEN'])){
session_start();
$_SESSION['CSRF_TOKEN'] = rand_csrf_string() ;
}
echo $_SESSION['CSRF_TOKEN'];
?>
Now when ever I refresh this session page, it is generating new token, I do not want token to get changed with every refresh or new page view. So can anyone help me with this?
Moving session_start(); to the top of your script will fix this problem for you. :)