I have the code to initialize the token:
session_start();
$token_string = bin2hex(random_bytes(32));
$_SESSION['token_'.$token_string] = time();
$token = $_SESSION['token_'.$token_string] = time();
The code to put a hidden input in my form
<form ... >
<?php
echo '<input type="hidden" name="token" value="'.$token.'" />';
?>
...
</form>
And the code to see if the token has been received correctly:
$max_minutos_csrf = 60;
$token_string = $_POST['token'];
if ( !isset($_SESSION['token_'.$token_string]) ||
$_SESSION['token_'.$token_string] < time() - $max_minutos_csrf * 1000 ) {
header('HTTP/1.0 400 Bad Request');
exit('Error de CSRF.');
} else {
// Ejecutar el resto de Php Mysql
}
It returns this error:
Notice: Undefined index: token_1491320450
If I do echo $_POST['token']
it gives me this: 1491320450
If I do var_dump($_SESSION)
it gives me:
array (size=7)
'user_session' => string '9' (length=1)
'token_f31339250d26b0e4af79749a6ecc56f2e7e1777b41d62b7472174b10443426fc' => int 1491322443
'token_7c65f80f5fb3d47d00b4480580edcbc7a60694018309f50f413bad16ed2634af' => int 1491322444
'token_87f9a9bfb2397f5c4b5b0865e3fcc513163a446bcb6cd47d8ac112e66f813b8b' => int 1491322445
'token_8ca703ee6144b88fc7df80ac46a669d109636f1a94acddb1a3db43a6c841382d' => int 1491322446
'token_082860bf9f77bfb159e97b0a8e17bfb71bf6bfc804e2bdf1572b45991424c0e3' => int 1491322699
'token_e4999ec00c11f9311f0778c38bfbfe8887a82907e386830d747af17be0b88ee2' => int 1491322700
Assuming that the function
time
returns the time insegundos
.Mistakes:
In the variable
$max_minutos_csrf
, as the name says, it is expected to be inminutos
and multiplying it by1000
, we obtain60.000 segundos
, which would be,1.000 minutos
or16.666 horas
.In the variable
$token
you are saving thetiempo
and not thetoken_string
one that you need to know if it exists in$_SESSION
.Solutions:
Multiply
$max_minutos_csrf
by60 (segs)
so that the value is inminutos
.Undefined index: token_1491320450
, may be due to:eg: session_start();
).session_set_cookie_params
There really is no value in
$_SESSION
.In your case it is the option
3
, to solve it you should print in thevalue
delinput
the$token_string
.Example:
PHP:
HTML