Reputation: 2893
I have seen questions on this topic but cant seem to find a solution. On my index page, at the top I am simply doing
<?php
session_start();
function generate_secure_token($length = 16) {
return bin2hex(openssl_random_pseudo_bytes($length));
}
$_SESSION['token'] = generate_secure_token();
$token = $_SESSION['token'];
?>
I then set $token
as a hidden field within my form. My question is relating to the processing of the form. At the moment I have
if ( empty( $_POST[ 'csrf_token' ] ) )
{
$errors['token'] = 'Something went wrong';
}
So it simply checks that a token exists. Is this enough? I have seen other examples recreating the token and then comparing it with the session token, but not sure if I need this?
Any advice on how I can validate this properly appreciated.
Thanks
Upvotes: 0
Views: 279
Reputation: 1717
You should compare the given token to your session token to be sure that the introduced token is valid:
if ( empty( $_POST[ 'csrf_token' ] ) ||
$_POST[ 'csrf_token' ] != $_SESSION['token'])
{
$errors['token'] = 'Something went wrong';
}
Upvotes: 1