Web Development Blog

How to stop form from submitting with page refresh using PHP

Problem 

Upon filling out and submitting the form, the user refreshers the webpage (F5) causing the form to be resubmitted and the entry to be rewritten to the database.
 
Fix 
 
This is not the only fix, but as I find it is one of the easiest
 
<?
session_start
();
/*Set session variable that will be used
  for checking if form is actually submitted*/
$_SESSION["resubmitForm"]=(empty($_SESSION["resubmitForm"]))?"1":$_SESSION["resubmitForm"];

if(!empty(
$_POST["process"]) &&
    !empty(
$_POST["resubmitFormValue"]) &&
    
$_SESSION["resubmitForm"]==$_POST["resubmitFormValue"]) 
{
    
$_SESSION["resubmitForm"]++;
    
//Other needed actions
}
?>
<form id="form1" name="form1" action="" method="post">
<input type="hidden" name="process" id="process" value="1">
<input type="hidden" name="resubmitFormValue" id="resubmitFormValue" value="
<?=$_SESSION["resubmitForm"]?>" />
<input type="submit" name="Submit" value="Submit" />
</form>
 
 
And one more suggestion, it make cense to check form submission by hidden input instead of submit button, because submit button value usually changed during development.

Michael Pankratov

Associated tags:  Web Development, Forms, HTML, PHP, Webpage, Sessions, Input

Comments:

Michael Pankratovs wrote on October 5, 2009 at 10:41

By using CAPTCHA in the form, you will fix this problem as well, because each time page loaded new CAPTCHA is created, and text entered in previous submission won’t be valid.


To find out what is CAPTCHA click here


To see how to implement CAPTCHA using PHP click here



rajeevs wrote on November 21, 2009 at 07:37
thanks

Rogers wrote on January 31, 2012 at 15:43
This is great!

Add Comment:

CAPTCHA