Re: Setting a cookie and redirecting

From: Date: Wed, 03 Jul 2002 00:32:42 +0000
Subject: Re: Setting a cookie and redirecting
References: 1  Groups: php.general 
Request: Send a blank email to php-general+get-105063@lists.php.net to get a copy of this message
Cord Schneider wrote:
Here is an outline of the problem: 1) client browser hits myPage.php 2) myPage.php does a few checks & recognises that this is a first visit 3) myPage.php sets a cookie using setCookie() 4) myPage.php redirects to checkBrow.php which uses JavaScript to do some basic browser detection 5) checkBrow.php does checks and looks for cookie written by myPage.php 6) checkBrow.php fails to find the cookie because header( "Location: http://someaddress" ) in step (4) has trashed the header containing the cookie information!! Note that ob_start() has to be used to prevent any data being sent to the client before the header has been set.. i.e. the page is being cached server-side.
This is a common problem people experience. When you use a "Location" header in this way, you not only add a simple HTTP header to the response, you also change the status code. The basic answer is, you cannot successfuly generate a "Set-Cookie" header and a "Location" header on the same page. This is a characteristic of the HTTP protocol, so you will find this in ColdFusion (cflocation) and other server-side scripting languages as well.
myPage.php was originally written in ASP and worked fine. ASP seems to write the cookie back to the client browser first, and *then* performs a redirect.
If you don't mind, I'm interested in learning more about what exactly ASP does differently. Are there two HTTP responses sent?
kludged a fix by setting the cookie and then writing a page that uses a <META> refresh to redirect... Is there a more elegant way of doing this??
That's the workaround most people end up with, and yes, it sucks. The best you can do for an elegant "solution" is to make your page completely white with a 0 second wait on the refresh, and it will be difficult to notice. Of course, those whose browsers don't automatically redirect will be staring at a blank screen. The "real" solution is usually to learn about all the limitations of the Web environment and try to design your solution around them. By your intelligent questions, I can tell you have a good grasp of what's going on, so I'll bet you can think of a slightly modified design that will work better for you. Happy hacking. Chris

« previous php.general (#105063) next »