0

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?

3
  • that means you are regenerating the token before comparison Dec 19, 2014 at 15:00
  • maybe use $_SESSION['form_token'] instead of $token in your input form.
    – Alex
    Dec 19, 2014 at 15:04
  • how come it regenerating new token when it already the same in value before it submitted. and i already put $_SESSION['form_token'] in my form but it just the same. the id is changing and i don't know why.
    – Eko
    Dec 19, 2014 at 15:09

2 Answers 2

0

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
  • thanks it work, but can you suggest me how i prevent it show error like this Notice: Undefined index: form_token in because this code : // compare the token if($_POST['form_token'] === $_SESSION['form_token']). it happen because i'm submit and submit again. thanks
    – Eko
    Dec 19, 2014 at 15:51
  • forget it, i commented in unset($_SESSION['form_token']); and it work, thanks again.
    – Eko
    Dec 19, 2014 at 15:58
0

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.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.