How to prevent form resubmission when page is refreshed (F5 / CTRL+R)
I would also like to point out that you can use a javascript approach, window.history.replaceState
to prevent a resubmit on refresh and back button.
<script>
if ( window.history.replaceState ) {
window.history.replaceState( null, null, window.location.href );
}
</script>
Proof of concept here: https://dtbaker.net/files/prevent-post-resubmit.php
I would still recommend a Post/Redirect/Get approach, but this is a novel JS solution.
Use the Post/Redirect/Get pattern. http://en.wikipedia.org/wiki/Post/Redirect/Get
With my website, I will store a message in a cookie or session, redirect after the post, read the cookie/session, and then clear the value of that session or cookie variable.
You can prevent form resubmission via a session variable.
First you have to set rand()
in a textbox and $_SESSION['rand']
on the form page:
<form action="" method="post">
<?php
$rand=rand();
$_SESSION['rand']=$rand;
?>
<input type="hidden" value="<?php echo $rand; ?>" name="randcheck" />
Your Form's Other Field
<input type="submit" name="submitbtn" value="submit" />
</form>
After that check $_SESSION['rand']
with textbox $_POST['randcheck']
value
like this:
if(isset($_POST['submitbtn']) && $_POST['randcheck']==$_SESSION['rand'])
{
// Your code here
}
Make sure you start the session on every file you are using it with session_start()