Prevent Duplicate Form Submission

You can use the method below to prevent duplicate form submission or form re-submission using PHP. This method is simple to implement and does not require JavaScript.

I will assume that the form is in the form.php file and the form submission is being handled by the form-exec.php script.

Modifying your form

Add the below PHP code to the top of the form.php script:

session_start();
$secret=md5(uniqid(rand(), true));
$_SESSION['FORM_SECRET'] = $secret;

In the PHP code above we create a unique ID using the uniqid() function and then create a 32 character hash of this unique ID using md5() function. Next we store this unique ID in the session for later use in the form-exec.php script. Remember to use a different session variable for each form.

Then add a hidden field anywhere in your form:

<input type="hidden" name="form_secret" id="form_secret" value="<?php echo $_SESSION['FORM_SECRET'];?>" />

Handling form submission

Compare the value of the hidden field with the value stored in the session. If the values match, process the form data. After processing the form data unset the value stored in the session. Now if the user refreshes the page, the form processing code will be skipped. See the sample code below.

session_start();

//Retrieve the value of the hidden field
$form_secret = isset($_POST["form_secret"])?$_POST["form_secret"]:'';

if(isset($_SESSION["FORM_SECRET"])) {
    if(strcasecmp($form_secret, $_SESSION["FORM_SECRET"]) === 0) {
        /*Put your form submission code here after processing the form data, unset the secret key from the session*/
        unset($_SESSION["FORM_SECRET"]);
    }else {
        //Invalid secret key
    }
} else {
	//Secret key missing
	echo "Form data has already been processed!";
}

Source

http://phpsense.com/2006/prevent-duplicate-form-submission/

Leave a comment