Skip to main content

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:

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:

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.

4 thoughts to “Prevent Duplicate Form Submission”

  1. Hi, thanks for this script it has been very useful for a site I am working on. But I think I have discovered an omission in your form-exec.php script above, shouldn’t you include “session_start();” at the top of this script?

  2. Thanks so much for the script.

    Just wondering how it could be modified to allow the form to be submitted, say 3 times, and after that to throw the error?

    1. Dan, that would be a simple matter of storing an integer (counter) in the session and incrementing it each time the form is submitted. When the counter reaches a certain value (3 in your case), we unset the FORM_SECRET from the $_SESSION array.

      Hopefully you can work it out from there. If not, let me know and I will see if I can update the tutorial to explain this.

Leave a Reply

Your email address will not be published. Required fields are marked *

*