Token Session and Post Token always different although from the same paramater

烈酒焚心 提交于 2019-12-12 04:49:10

问题


i'm generate a token for my form like this:

/*** set a form token ***/
$token = md5( uniqid(rand(), true) );


/*** set the session form token ***/
$_SESSION['form_token'] = $token;

and put hidden input in my form like this:

<input type="hidden" name="token" value="<?php echo $token; ?>" />

but when i submit the pages and compare the token it give me a different token id. can anyone tell me am i doing something wrong?


回答1:


Make sure you only (re)generate a token if the form is not submitted yet.

<?php
// Process request OR show form..
if($_SERVER['REQUEST_METHOD'] === 'POST') 
{
    // check if we receive a token
    if(isset($_POST['form_token'])) 
    {
        // compare the token
        if($_POST['form_token'] === $_SESSION['form_token']) 
        {
            // do the magic here...
            unset($_SESSION['form_token']);
        } else {
            die('No token match');
        }
    } else {
        die('No token found');
    }
} else {
    $token = md5( uniqid(rand(), true));
    $_SESSION['form_token'] = $token;

    // print form with hidden token..
}



回答2:


Try visiting your site in an incognito window. If this works, you need to delete all your browsers' cookies and other site plugins because your session has been cached. It's trying to match sessions from an earlier time.



来源:https://stackoverflow.com/questions/27568547/token-session-and-post-token-always-different-although-from-the-same-paramater

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!