PHP redirect craziness

PHP programming forum. Ask questions or help people concerning PHP code. Don't understand a function? Need help implementing a class? Don't understand a class? Here is where to ask. Remember to do your homework!

Moderator: General Moderators

Post Reply
ZHarvey
Forum Newbie
Posts: 3
Joined: Wed May 05, 2010 7:03 pm

PHP redirect craziness

Post 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
User avatar
requinix
Spammer :|
Posts: 6617
Joined: Wed Oct 15, 2008 2:35 am
Location: WA, USA

Re: PHP redirect craziness

Post 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
Post Reply