How to stop form from submitting with page refresh using PHP

August 10, 2009

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