Page 1 of 1

PHP redirect craziness

Posted: Thu May 06, 2010 12:21 am
by ZHarvey
Hi,

Because I couldn't find anything better, I wrote a quick-and-simply PHP function to handle server-side page directs that my web app can incorporate into its business logic:

Code: Select all

function PhpRedirect($newUrl)
{
	$sub = SUB_DOMAIN;
	$website = WEBSITE;
	header("Location: http://$sub.$website/dts/$newUrl");
}
So, if SUB_DOMAIN = "www" and WEBSITE = "abc" then a call to <b>PhpRedirect("bizarro.php")</b> results with you being navigated away from the current page and to <i>http://www.abc.com/bizarro.php</i>.

Hate it or love it, I tested it quickly and it was working fine.

Until...

You put two of these function calls back-to-back:

PhpRedirect("dog.php");
PhpRedirect("cat.php");

You'd think that it would execute the first statement, redirecting you away from the (this) current page, preventing the second redirect from ever executing, right?

Wrong! You end up at cat.php!

The best I can surmise is that (and I'm a little weak on my HTTP theory), but perhaps headers are universal, and don't have anything to do with the document object (the page that is being construced).....?

Anyways, please let me know if you have any ideas as to what is happening, and how I can change this.

<b>Edit: I realize now that header()s must be the first output in the file, else they dont work quite right. So I guess this post has become "how to redirect without header?" Google didnt turn up anything useful...</b>

Thanks,
Z Harvey

Re: PHP redirect craziness

Posted: Thu May 06, 2010 12:54 am
by requinix
- Headers aren't sent immediately.
- Headers always precede output. If output has started it's too late to send additional headers.
- Redirecting is not a command. It's a message sent to the browser, just like content types and file downloads.

HTTP