PHP: Page Redirecting with Header… and Die() CodeUnit 25 OCT 2010

php elephant iconI 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');

A simple tip, but one worth remembering.

Related Link:

Related Posts:

About Craig Lotter

South African software architect and developer at Touchwork. Husband to a cupcake baker and father to two little girls. I don't have time for myself any more.