What are some methods to prevent double posting in a form? (PHP)

Posted by jpjp on Stack Overflow See other posts from Stack Overflow or by jpjp
Published on 2010-05-25T02:57:50Z Indexed on 2010/05/25 3:11 UTC
Read the original article Hit count: 265

Filed under:
|

I want to prevent users from accidentally posting a comment twice. I use the PRG (post redirect get) method, so that I insert the data on another page then redirect the user back to the page which shows the comment. This allows users to refresh as many times as they want. However this doesn't work when the user goes back and clicks submit again or when they click submit 100 times really fast. I don't want 100 of the same comments.

I looked at related questions on SO and found that a token is best. But I am having trouble using it.

//makerandomtoken(20) returns a random 20 length char. 

<form  method="post" ... >
<input type="text" id="comments" name="comments" class="commentbox" /><br/>
<input type="hidden" name="_token" value="<?php echo $token=makerandomtoken(20); ?>" />
<input type="submit" value="submit" name="submit"  />
</form>

if (isset($_POST['submit']) && !empty($comments)) 
{
    $comments= mysqli_real_escape_string($dbc,trim($_POST['comments']));

    //how do I make the if-statment to check if the token has been already set once?
    if ( ____________){ 
        //don't insert comment because already clicked submit
    }
    else{
        //insert the comment into the database
    }
}

So I have the token as a hidden value, but how do I use that to prevent multiple clicking of submit.

METHODS: someone suggested using sessions. I would set the random token to $_SESSION['_token'] and check if that session token is equal to the $_POST['_token'], but how do I do that? When I tried, it still doesn't check

© Stack Overflow or respective owner

Related posts about php

Related posts about mysql