Prevent form from being submitted twice

10,013

Solution 1

You should perform a REDIRECT to a page with a message that the data was inserted... and a back button to go to the form again (if you want to)...

To redirect using PHP use the header function:

header('Location: http://www.example.com/');

Solution 2

Perform a redirect after the data is inserted to a confirmation page (can be done with header(), which should clear out the POST data and allow for refreshing without duplicating content.

Solution 3

In the case of user having lag and he hits the submit button a few times, then maybe use client side mechanism, use js to set the submit button to disabled once it is clicked. but will have to display message saying roughly something like, "sending message ... if no response pls reload page and retry".

Share:
10,013
Alex
Author by

Alex

I'm still learning so I'm only here to ask questions :P

Updated on July 23, 2022

Comments

  • Alex
    Alex almost 2 years

    I have a simple php form, like this:

    <?php
    
    if(isset($_POST['myform']))
       // email...
    else
       // display form
    

    the problem is that if I refresh the page after I submit the form, it gets submitted twice. How can I prevent this from happening?

  • BalusC
    BalusC over 13 years
    This is by the way called the Post-Redirect-Get pattern.
  • Alex
    Alex over 13 years
    thanks. but now I have another problem :) I added header('Location: http://www.example.com/?formsent=1');, and I'm checking for $_GET['formsent'] to display a success message. The problem is that if I refresh the page I get the same success message :)
  • Garis M Suero
    Garis M Suero over 13 years
    and the problem is?... i don't see it as a problem, as it doesn't manipulate any data on the DB.
  • amaster
    amaster over 10 years
    sometimes the simplest answers are the best because most people including myself tend to over complicate matters. Thanks!
  • rayryeng
    rayryeng about 7 years
    Please give some explanation as to what is going on in the code. Code dumping is frowned upon here.