Anna Filina

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.

Comments

Juan February 5th, 2010 Hi,

I was trying to deal with this matter but I gave up as I could not understand it properly.

The solution I have seen is related to the session. when you submit a form then you save the values in a session and then empty the values in the form so the page will not resend the values again when it is refreshed.

Now I am seeing in your blog that this solution would not be good enough.

I would appreciate if you may explain me this problem.

Thanks a lot,

Juan
Anna February 8th, 2010 Sorry for the late response.

The problem with storing your data in the session for every post is that it's an extra operation that has no real value and can be easily avoided. Also, when you have multiple tabs open with the same form, you may get unexpected results. Last, there may be some data that you would never for the world want to store in a session, such as a password or a credit card number, because they will be unencrypted and in a vulnerable session file (unless your sessions are in DB, but you still have the encryption issue).

Redirection after the post data has been processed is a standard approach used by many renowned PHP frameworks that I have worked with since I posted this article.
andrew May 4th, 2010 Hi Anna have you got a code example you could share, am a newibe and not sure I can picture it right.

Thanks
php thumbnailer May 21st, 2010 I am using sessions too to avoid that.
omer October 29th, 2010 i didnt get it :)
Mehdi Hanbali December 13th, 2010 Great idea Anna. I've read in other places about using redirect, but not with the appending of that variable. To elaborate, here is one way you can do it.

In your form have it something like:

At the very top of your php page, before anything is outputted to the screen do something like:

$old_submit = $_GET['submit']; // this gets the submit variable you appended in your form
$current_url = 'samepage.php'
if ($old_submit == "true") {
header("Location: $current_url");
$old_submit = "false";
}

Let me know if you have any questions or better ways of doing it.

-Mehdi (letdev DOT com - launching december 17th, 2010)
Ivan Panchev June 17th, 2011 Thank You Anna this is verry good(the best) solution :). Sessions are not good in this case. They can produce great pain. So:



...





I believe this is it. Great! I'll try it now :)
Ivan Panchev June 17th, 2011 I believe this is the code:

file 1 - with the submission form
form ... action="file2.php?submit=true>
...
Antoinette asaad July 28th, 2014 Thank you
meh August 25th, 2014 I just couldn't figure out what the sentence "use header(“Location: …”) with the current URL means.
Where do I put it? Inside my processing file? Inside my form page? With what url? ...?
Anna August 29th, 2014 header("Location: ...") goes into your PHP script at the point where your form is finished processing (like saving data to the database). The URL you put there is up to you. It typically point to a page that says "your data was saved", to a list or to a details page.

For example, if I want to use a form to create a blog post, you would process your form, save the blog post and then tell your PHP this:
header("Location: blog/view-article/{$id}")
Kim October 25th, 2014 Can't I just use Post Redirect Get without the `?submit=true` ?

See http://en.wikipedia.org/wiki/Post/Redirect/Get for explanation of PRG.
Anna October 28th, 2014 This is only needed when you redirect to the same script, in order to distinguished processed from unprocessed requests easily. If you redirect to a different script, then you don't need the distinction.

If you're using a framework with routing, then you can achieve something similar by redirecting to another action in your controller, such as editComplete.

The reason why I advise against redirecting after a successful save using POST is because the browser will prompt the user to resubmit, causing confusion.
Refresh form but do not resubmit (PHP) | Information and Computer Technology Problems December 6th, 2014 […] Source: http://afilina.com/refresh-form-but-do-not-resubmit-php/comment-page-1/ […]
doc truyen February 25th, 2015 Thank you!
I needed code location
At March 4th, 2015 Hello,

I think,when you insert form-data,put insert in condition if condition true then redirect it resp.URL in this way you can prevent multiple entry made by multiple click on submit buttion.

Hope it will help you.

Thanks,
At
matteo April 1st, 2015 With the global $_SERVER you don't have to manually handle the redirection URL:
header("Location: " . $_SERVER['REQUEST_URI']);
Bob April 22nd, 2015 This is great, however I cannot get it to work. I've appended "?submit=true" to the form action and have included the "header(“Location: …”) " script at the end of the php processing script.

I'm confused on how the header redirect would work if it is not placed at the very top of your page (before any output). Anyway, I'm certain it works for you, but I not for me.

Thanks
Mark April 29th, 2015 Interesting solution. It seems pretty neat and quick. Will try this one. Thanks for sharing.
Anna April 29th, 2015 This is actually a Post/Redirect/Get. That's why we redirect to a ?submit=true. You can redirect to a completely different URL too.

This article was written before MVC frameworks became widespread and when URL rewriting wasn't very common. In 2015, you would most likely redirect to a completely different URL because routes have become cheap.
Anna April 29th, 2015 Shortened example:

if (isset($_GET["submit"])) {
echo "Saved!";
}
else if ($is_post && $is_form_valid) {
saveToDatabase();
header("Location: " . $_SERVER['REQUEST_URI'] . "?submit=true");
}
else {
displayForm();
}
daniel ziskin June 12th, 2015 My situation is strange and not quite fitting into this thread but somewhat related:

I'm trying to pull data from some server that I do not have direct access to. For some reason that I don't understand cURL fails. When I don't include all the POST variables the form just returns itself. When I do include all the POST variables I get a server error without the data. It only works when I display the website and press the submit button. Also, I have not been able to get file_get_contents() to work either.

Is there some other way to get the data
1) Select and copy the displayed data after the browser has rendered it?

2) Refresh the page and send it to a variable instead of re-displaying it? something like:
$results = header($currentURL);

3) Something else?
Anna June 12th, 2015 Your setup and purpose is really not clear to me. Are you trying to send an HTTP request to a 3rd party? Perhaps seeing some code would help me understand what you're doing. Open a more detailed question on StackOverflow and post the link here.
Shah July 30th, 2015 i am a big fan of you.thanks ...i got help from your post..first time to comment
softphoton October 24th, 2015 hello when i refresh the site
Charlie November 15th, 2015 Very helpful all that you do in this article. Whats more this article is from 2007 and you're active in here, cheers from Florida! -Carlos
Arshid Ali November 23rd, 2015 Hello when i insert data into database the data is saved in database but when i refresh the page the same data is inserted again i mean duplication of data can you tell me what i do now. answer me on arshid.uop@gmail.com
kushmeet December 7th, 2015 Plzz help,
the prob is ,I don't want my form to be resubmitted again and again after i press refresh command or reload.
and the most important is i want this prob to be solved with the help of LAST_INSERT_ID().
help out as soon possible.
jigi December 18th, 2015 hi i need ur help how to i stop resubmit where i m refresh the page
jigi December 18th, 2015 header('Location:http://localhost/jigi/ad.php');
i m write this but data resubmit in database
bhaskar January 14th, 2016 hello hi
how to get same page after refreshing in php
Rahul February 10th, 2016 This was a good solution i did it this way



and in php

if( isset($_GET['submit']) && ($_GET['submit']=='true') )
{header('Location: users.php');
}
Rahul February 10th, 2016

here is the html code
lazyexpert February 15th, 2016 I've solved this with JS. Somewhy this was easier:

document.addEventListener('DOMContentLoaded', function (e) {
if( /submit/.test(window.location) )
window.location = "/upload.php"
})

paulnoris April 4th, 2016 GOOD CONTRIBUTION
joao April 5th, 2016 HELP !!!

So i've created a page which has a table displaying the days of the week + details + activity & client.
it's basically a timesheet where the employees ADD or EDIT their timesheet.

The data gets stored on a database with MSSQL and is pulled back into this PHP page using a class that contains T-SQL queries.

the problem is when adding or editting the page if I click refresh it adds again and again.

I know there are many ways stated above to solve this issue BUT if i achieve to resubmit my page; which works really well !!!!! theres ONE big problem. it takes me back to the initial page not the actual page I was on editing. The way the page works is that you select a week within a datepicker and it
pulls out the corresponding data into the table, but If i resubmitting to the page to prevent the refresh error it doesn't return me to the date I'd chosen instead it brings me back to the most current timesheet in
the calendar.
Ramya April 15th, 2016 Hi anna,

I have created a html form with 2 text boxes also i given the basic javascript validation like fields are empty then it will show error message..the problem is if i keep the first box empty and hit the submit button it showing the error message correctly at the same tiime the page also reloding...how to solve this problem ??
Frank May 26th, 2016 Hey guys / Hey Anna,

I was looking for a solution for exactly that problem and implemented yours - now (it's probably a beginner error) I got: "Cannot modify header information - headers already sent blabla". Someone got a solution for this? I have already read sth about it on other sites and there it says "don't include anything before posting that header information". Now this somehow contradicts the instruction that it should be placed right after the process has been finished.

What am I doing wrong :/?

Greetings!
Anna June 21st, 2016 Something somewhere is sending output. One common error I see people make is adding a newline before the opening PHP tag. Double-check that.

If not, view your page's source and see what hidden output is there. This can give you clues as to where the output may have been sent from.
Anna June 21st, 2016 If I understood correctly, your page redirects whether there is a success or not, since your validation is done on the JavaScript side only. In that case, there is a JavaScript command called event.preventDefault() that you would call in your submit button listener. That would disable the default behaviour of the button. When there are no errors, then you would just call form.submit() to let the browser take over.

However, for security purposes, I would strongly advise you to also validate on the PHP side, otherwise people could disable JavaScript and throw garbage data at your form.
Harish June 27th, 2016 Hello Anna

In first page, I am listing all 'items' list and adding a 'view item' button for each item. I am posting a hidden input for 'item id'. When a user click on 'view item' button, the respective 'item id' will be posted to second page and there, all the data of respective item will be fetched from database and displayed.

Now, when user refreshes second page 'resend form data?' is prompting. I want to avoid this. Can you please give a solution?
تولیدی مانتو September 10th, 2016 Thank you
sharad yadav November 1st, 2016 i am working on a project of online paper and i wanna disable the refresh button of my browser on paper page.
amin December 31st, 2016 thank you
kakdiya dilip February 18th, 2017 stop insert data in database when refresh page in php
Nigel April 22nd, 2017 Is it really necessary to specify a query in the relocation URI? I seem to have achieved the same effect with just header("Location: " . $_SERVER['REQUEST_URI'] . "?");The '?' alone is enough to force a GET method, isn't it?
Maathr May 2nd, 2017 Hi Anna
i want to build web page for online Quiz, But I had a problem
the problem is if the Student click refresh before click "submit"
i want resume the data that he already input it
adultfriendfnder June 5th, 2017 Howdy fantastic website! Does running a blog
like this take a lot of work? I have no expertise in computer programming however I had been hoping
to start my own blog in the near future. Anyways, should you have
any ideas or techniques for new blog owners please share.
I understand this is off subject however I simply had to ask.
Cheers!
Chamath Fernando July 19th, 2017 Hi Anna,
First of all thank you for the solution. As you have mentioned above, most of the solutions were about using a session to refresh the form without making it re-submit. But your way of doing it is the simplest and the efficient. And is there any way to add an alert to this in order to inform the user that the form has been submitted? I tried using it with your solution, but could not figure it out.
steam August 29th, 2017 Ꮐood post. Ӏ am experiencing many of tһese issues as well..
Khomba August 31st, 2017 Thats work perfect. this problem has been solved once and for all by that code.
اینترنت اشیا September 18th, 2017 hi i have created a html form with 2 text boxes also i given the basic javascript validation like fields are empty then it will show error message..the problem is if i keep the first box empty and hit the submit button it showing the error message correctly at the same tiime the page also reloding…how to solve this problem ??
ALex Petrov September 27th, 2017 Works great. Thank you!
Marcos December 26th, 2017 Thank you very much! This worked perfectly here. Your solution is simple and effective.Congratulations!
PhillipNaf February 4th, 2018 Sorry send a little money MasterCard 5106 3845 2180 6323
amkhani April 23rd, 2019 hi guys i have a project in the end of my study
i have problem in my web page when i click
any button for exemple button for share comment
the page refresh what is the solution of this issue .
i tried to do all the thing above but no result


This page is protected by reCAPTCHA and the Google
Privacy Policy and Terms of Service apply.

Phone: +1 514-918-7866 | E-mail: anna.filina@zenika.com