Sometimes, we want to prevent form resubmission when the page is refreshed (F5 / CTRL+R) with PHP.
In this article, we’ll look at how to prevent form resubmission when the page is refreshed (F5 / CTRL+R) with PHP.
How to prevent form resubmission when the page is refreshed (F5 / CTRL+R) with PHP?
To prevent form resubmission when the page is refreshed (F5 / CTRL+R) with PHP, we can create a random session variable and check that.
For instance, we write
<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>
to create a random number and assign it to $_SESSION['rand']
.
And then we put the $rand
value in a hidden input field.
Then we check if the $_SESSION
[‘rand’]value matches
$_POST[‘rand’]` before we allow submission.
To do this, we write
if(isset($_POST['submitbtn']) && $_POST['randcheck']==$_SESSION['rand'])
{
// ...
}
to compare both values with $_POST['randcheck']==$_SESSION['rand']
.
If they match, then we continue with submission.
Conclusion
To prevent form resubmission when the page is refreshed (F5 / CTRL+R) with PHP, we can create a random session variable and check that.