PHP: Page Redirecting with Header… and Die()

I make use of PHP’s handy header function to handle simple page redirects for me, perhaps a bit of a cheap way of doing it, but one that is remarkable effective. Sure, you need to change the way you code a little and perhaps introduce some ob_start and ob_end_flush calls if necessary, but on the whole a good old header(‘Location: newpage.htm’) call works pretty damn well.

But here’s a handy note, something to keep in mind when redirecting to a new page using the header function.

Sometimes, somehow, somewhere, a browser script might/will/does continue silently running even after you called your header relocate function, introducing some potentially hazardous side affects because some or other critical session variables or something or other have been set to something they simply weren’t meant to be.

Often this is noticeable with login processing backend scripts, where logins will mysteriously work or fail depending on your set up, occurring purely because session variables have been set when you didn’t think they would be because according to you, the page had already redirected.

So a simple solution to this?

Well the reliable little die() statement works pretty damn well in this case. So the resulting code?

header('Location: newpage.htm');
die();

A simple tip, but one worth remembering.

Related Link: http://php.net/manual/en/function.header.php

You might also enjoy:

About Craig Lotter

Craig Lotter is an established web developer and application programmer, with strong creative urges (which keep bursting out at the most inopportune moments) and a seemingly insatiable need to love all things animated. Living in the beautiful coastal town of Gordon's Bay in South Africa, he games, develops, takes in animated fare, trains under the Funakoshi karate style and for the most part, simply enjoys life with his amazing wife and daughter. Oh, and he draws ever now and then too.
This entry was posted in Technology & Code, Tutorials and tagged , , , , , . Bookmark the permalink.
    blog comments powered by Disqus