Avoid resending forms on php pages

Solution 1:

Use the Post-Redirect-Get Pattern.

  1. Accept a Post request
  2. Process the data
  3. Issue a redirect response
  4. Accept a Get request
  5. Issue a 200 response

If you need to display data from the submitted stuff, then include a row id or similar in (for example) the query string of the URL you redirect to.

Solution 2:

The best way would be to do a header("location: form.php"); call after you process the form. That would redirect you back to the form page, and if you refresh, the browser wont resend the form data.

Alternatively, you could check to see if you already processed the data received, but that would still give you the browser warning message that you are going to resend the data.

You might do both, just in case someone uses the back button and accidentally clicks Submit again.

Solution 3:

Just set some flag when you process the form first time so you could check for it and abort reprocessing later on. Session variable or cookie will work fine.