简体   繁体   中英

CSRF Token validation when processing

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

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';
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM