Reputation: 575
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
Upvotes: 2
Views: 3801
Reputation: 483
you can do also in jquery it's very simple.
$(document).on('click', '.className', function(){
$(this).css( 'pointer-events', 'none' );
});
Upvotes: 0
Reputation: 97805
If you want to prevent double submissions, you must store the state of "is submitted" versus "is not submitted". You have several options for where to keep this information.
Upvotes: 7
Reputation: 33592
I'd skip the whole random token thing and just store (a hash of) the comment in the session. If it matches the existing value stored in the session, then drop the comment. If not, let it through. Obviously there are problems:
You might want a random token to prevent XSRF anyway, but that's another issue (and in that case, you want to make sure that the random token is the same as "what it should be"; I'd store a long-lived one in the session).
Also, consider using prepared statements.
Upvotes: 0