My friends and family are under attack in Ukraine.
Donate to protect them directly or help international organizations.

Refresh form but do not resubmit (PHP)

September 3rd, 2007

This question has been asked so many times that most of you don't want to hear it again. Unfortunately, the solutions that people are proposing are less than ideal.

For those who are new to the concept, a quick explanation is in order. You have a form that you display, validate and act upon (send e-mail, save to database, upload files, etc.) Once this is done, the user might refresh the page and you will end up with duplicate entries.

Bad ideas to handle it are: splitting into multiple files to work around this problem, using the meta-refresh tag, setting unique identifiers and store them in session or in hidden fields, checking for duplicates after resubmission, using javascript…
If you want to know why they are bad, just post a comment and I will give you a detailed explanation of the particular case.

I found a quick and neat way to do it (perhaps I'm not the first, but I feel the need to share it). Append "?submit=true" to your form action and use header("Location: …") with the current URL. Thus, once form data has been saved, you will be redirected to the same page without the POST variables. If PHP complains that output was already sent, then you have a bad approach for your output. I usually store all my output in a variable(s) and echo it when everything is okay. More on output in another entry.

Previous: Do we have to do it all in a text editor? Next: AI: Manipulating images in a whole new way