Coding with Jesse

Redirecting after POST

May 22nd, 2007

When working with forms, we have to think about what will happen when someone clicks back or forward or refresh. For example, if you submit a form and right afterwards refresh the page, the browser will ask if you want to resend the data (usually in a pretty long alert box talking about making purchases).

People don't always read alert boxes, and often get used to clicking OK all the time (I know I fall in this category), so sometimes comments and other things get submitted more than once.

To solve this, you can simply do an HTTP redirect after processing the POST data. This is possible with any server-side language, but in PHP it would look something like this:

if (count($_POST)) {
    // process the POST data
    add_comment($_POST);

    // redirect to the same page without the POST data
    header("Location: ".$_SERVER['PHP_SELF']);
    die;
}

This example assumes that you process the form data on the same page that you actually want to go to after submitting. You could just as easily redirect to a second landing page.

On this site, on each blog post page, I have a form that submits to the same blog post page. After processing the comment, I send a redirect again to the same page. If you add a comment and then refresh, or click back and then forward, the comment won't be submitted twice. (However, if you click back and then click Add Comment again, it will. I really should filter out duplicates, but that's another topic.)

This works because you essentially replace a POST request with a GET request. Your browser knows that POST requests are not supposed to be cached, and that you should be warned before repeating a POST request. After the redirect, the page is the result of a simple GET request. Refreshing the page simply reloads the GET request, leaving the POST request lost between the pages in your browser history.


Interested in web development? Subscribe to my newsletter!

Comments

1 . dave at 2007-06-22T04:31:08.000Z

dave

wonderful. i have been doing self-redirect after post for along time and i can say that this is the single most important use of redirect!! thank you for your clear explanation! im sure it will help many

2 . _ck_ at 2007-08-04T12:21:29.000Z

_ck_

The only problem with this technique is that if you are using a CMS/blog that has to preload all it's code before a template is displayed, you essentially are causing twice the load because you are loading it twice (once for processing the post data, then the second time when you externally redirect back to itself).

Multiply this by a hundred people doing it at once on a busy site and your server will feel it.

I've am digging into the problem and it occurs to me there might be a way to clear post data on the client-side via javascript. Would cause zero extra server load. More research needed!

3 . nash at 2007-09-14T07:05:22.000Z

nash

nice explanation. but this is what i get when i use this. ive been getting it before and i thought this would be a solution. it didnt solve it though. please let me knw how u can do that.
many thanx in advance:

Warning: Cannot modify header information - headers already sent by (output started at some-url-page.php:10) in myfilename.php on line XX

4 . Jesse Skinner at 2007-09-14T09:36:49.000Z

Jesse Skinner

@nash - Sounds like the problem is some HTML or text has been outputted before you do header("Location") - and I bet that happened on line 10 of some-url-page.php.

Just make sure the header() function is called before anything gets outputted.

5 . Jesse at 2007-11-08T20:01:39.000Z

Jesse

I want to use this method, and I know I've successfully used it in the past. But the problem I'm having now happens after the POST data is handled -- when the "Location: " header is sent, Firefox prompts me about whether I want to re-send my post data to the GET destination (which I don't of course - that's the problem I'm trying to avoid!) and the page goes blank if I answer 'No'. This is not a problem in IE. Any ideas?

My POST operation has the action "/home" and my redirect looks like "/home/eID/[some_id]". Thanks in advance!

6 . Manoj Sonawane at 2007-11-28T04:41:52.000Z

Manoj Sonawane

i want redirct page to itself when some one change to and add process to this page

7 . jauco at 2007-12-10T13:33:14.000Z

jauco

this is of course begging for a test ;-)

But seriously, I was thinking about using GWT just to avoid this (major) problem of postdata.

8 . jauco at 2007-12-10T13:35:06.000Z

jauco

and this solution seems much better, thanks!

(It apparently doesn't stop you from pressing the submit button to early though)

9 . vicky at 2008-01-05T13:42:55.000Z

vicky

Hi,I have doubt in jsp..i need to redirect the same page after inserting the data in to database....can u help me....Before that it ll be d inserted successfully,no need dis type of method.....

10 . Jesse Skinner at 2008-01-05T14:47:52.000Z

Jesse Skinner

@vicky - I'm not that familiar with JSP, but a quick Google search for 'jsp redirect' gives the following example:

String redirectURL = "http://hostname.com/";
response.sendRedirect(redirectURL);

So you'd replace the redirectURL with the URL of the page. I hope that helps!

11 . Bob at 2008-02-03T12:50:21.000Z

Bob

Great solution of this annoying problem! Thank you.

12 . vicky at 2008-02-13T06:34:58.000Z

vicky

Hi jesse...i had one doubt...In(JSP & HTML) List out box,four options r there,i used option tag for select dat but its inserting in d database.....But mine doubt is, i have to select Multi more option in dat List out box,I donno wat option s dat...Can u clarify mine doubt(JSP)

13 . Prabath at 2008-04-01T08:38:11.000Z

Prabath

Although this didn't directly help me solving my "Clearing post data when back to the original page", it helped me to device a method to solve the problem.

Thank you very much for your valuable teachings.

14 . Patrick Moore at 2008-04-22T18:44:25.000Z

Patrick Moore

@ck : Assuming you aren't parsing scores of variables, you could pass along the same information as GET variables to be interpreted by the destination.

In example, a blog comment form:

if (count($_POST)) {
// process the POST data
add_comment($_POST);

// Collect and pass through variables
$subject=$_POST["subject"];
$name=$_POST["name"];
$url_append="?subj=$subject&name=$name";

// redirect to the same page without the POST data but with the variables
header("Location: ".$_SERVER['PHP_SELF'].$url_append);
die;
}

if ($_GET["subj"] && $_GET["name"]) {
// Read in the variables we passed via the URL
$subj=$_GET["subj"];
$name=$_GET["name"];

// Notify the user of action
echo "Thank you, $name. Your comment ($subj) has been recorded.";
}

15 . Patrick Moore at 2008-04-22T18:47:34.000Z

Patrick Moore

An afterthought: You could set cookies for bulkier or session variables for sensitive data to be interpreted at the destination page. Yes it would increase server load some, but wouldn't require duplicate database queries... and cookies would incur little to no extra server load other than parsing variables.

16 . dersleri eÄŸitimi at 2008-06-24T12:04:24.000Z

dersleri eÄŸitimi

About Redirect to other web address // html code --

http://html-lesson.blogspot.com/2008/06/redirect-to-web-addres.html

17 . Krech Ion at 2008-07-12T13:36:04.000Z

Krech Ion

Hy, I have this problem. I submit a login form with the POST method, and after that the redirect example that you gave should take my to the page that I'm looking for, instead I get a blank page. If I hit the reload button, then the page is loaded, after the usual message from IE or Firefox.

Any help would be appreciated!

18 . George at 2009-02-28T07:49:13.000Z

George

Why I get: Call to undefined function add_comment()
Where is this function?

19 . Jesse Skinner at 2009-02-28T10:25:38.000Z

Jesse Skinner

@George - add_comment is just an example of what you might want to do with POST data. Replace with your own form processing code.

20 . cmnorton at 2009-04-02T22:03:32.000Z

cmnorton

Are these code samples javascript or php?

21 . Jesse Skinner at 2009-04-04T13:16:56.000Z

Jesse Skinner

@cmnorton - that's PHP being used. I wouldn't recommend depending on JavaScript for this behaviour.

22 . Robin at 2009-10-27T04:26:18.000Z

Robin

Hi Jesse just wanted to know how I can implement your php redirect in a couple of my pages for a website I'm building. If you'd like to have a look at the site you can visit it at http://postcardsfromheaven.co.nz I already have some php code in my message_board.php page and I'm not sure where to place the code together with mine.

23 . Jesse Skinner at 2009-10-27T15:59:13.000Z

Jesse Skinner

@Robin - It all depends on when you want to redirect, and how the PHP file is structured. You can put the code anywhere, but typically try to figure out where the form is processed and stick the redirect somewhere immediately afterwards.

24 . Robert Thornton at 2009-11-23T17:30:44.000Z

Robert Thornton

Only now it seems that Firefox 3+ helpfully resubmits your POST request if you hit refresh after a GET redirect.

Not quite so clear anymore.

25 . colkaster at 2010-03-12T14:49:55.000Z

colkaster

i agree with last post it`s very interesting.

26 . Rama at 2010-09-29T01:40:52.000Z

Rama

wanted to know how to redirect after submit without having a back to mainpage option (no other click required) once the submit is clicked it should automatically go the previous page

Thanks in Advance

27 . Mathieu Parent at 2010-11-14T08:19:33.000Z

Mathieu Parent

Hi there, if you want your page to redirect to the previous page you could always use the http referer, but it is unreliable. The best would be to have a hidden input storing what the next page should be or having your form processing code handle it by itself... There is a ton of possibilities, just explore the options!

28 . Brian Crumby at 2011-05-20T21:29:30.000Z

Brian Crumby

can this redirect to another web page after the form data has been emailed?

29 . Jesse Skinner at 2011-05-20T22:08:04.000Z

Jesse Skinner

@Brian - absolutely. In the place where the add_comment() function is being called, you could easily to a call to mail() to send off an email. Just be sure not to 'echo' out anything before you do the redirect, or it will fail.

30 . Brian Crumby at 2011-05-20T22:47:04.000Z

Brian Crumby

well it did not work for me :( I am about to give up on the form and just do the redirection

when form data is filled out I am trying to email it to an email and then redirect the page to an mortgage application link

the PHP code looks like ...


<?php


echo ("started script .... ");

if(count($_POST))
{
echo ("post counting .... ");
header("Location: https://fpproc.flexapp1003.com/LoanApp/English" );
die;
}

if ($_GET["name"] && $_GET["email"])
{

$namooo=$_GET["name"];
echo ("Got name & email ... ");
echo ($namooo);

}

?>

<script>

//window.open("https://fpproc.flexapp1003.com/LoanApp/English")

</script>

the error msg is ....

Warning: Cannot modify header information - headers already sent by (output started at /home2/fpprocco/public_html/mmot/contact-apply.php:3) in /home2/fpprocco/public_html/mmot/contact-apply.php on line 4
started script .... Got name & email ... brian crumby8

31 . Jesse Skinner at 2011-05-20T23:23:37.000Z

Jesse Skinner

@Brian - yes the error you are getting is what I warned about - do not do any echos before you use header() or it won't work.

32 . brandon at 2011-06-16T16:09:25.000Z

brandon

what if i want the script to redirect to a basic html page? what would the syntax look like?

33 . Jesse Skinner at 2011-06-16T16:48:55.000Z

Jesse Skinner

@brandon - same thing, eg.

header('Location: basic.html');
die;

34 . cyruz at 2011-11-10T03:58:20.000Z

cyruz

thx for the info <em>:D</em

35 . gilbert at 2012-01-19T01:10:45.000Z

gilbert

Hi Kinny,

I Hope you can help how to do a page like this one where user can add a comment and visible right here already.


Thanks in advance.

36 . anil at 2012-08-02T11:53:27.000Z

anil

What is URL REDIRECTION?How can i use this concept in my .net?
my task is i have generated one url like this "http://example.com/"
I am passing one pearameter like "http://example.com/Empno=1"
I want to display Ename in Database table that corresponding "Empno"
plz Help me Give me one simple example

I am new this concepts
plz Help me send source code to my mailID:[email protected]