View Full Version : header(location) behavior-- code continues to execute?

01-28-2010, 04:47 AM
It appears to me, at least on my local xampp web server, that header("location:$url"); does not kill the script. PHP code further on down the line executes beyond the header() call before the header() call has a chance to kick in and redirect to another URL. I've always assumed it's just like calling die()-- any code after the header("location:") will never execute. But this apparently is not so!

Can anyone explain this? I spent a couple of hours fiddling around before realizing this was happening. (And yes, I realize it's not good coding practice to end my script with header() but that's the nature of this particular beast)

01-28-2010, 04:55 AM
It's a bugger the first time you realise that, ain't it. :D It wouldn't be much use if issuing a header call killed the script. exit() every time if you want processing to stop there and then.

01-28-2010, 10:56 AM
Header may be used to send all sorts of things and having it die or exit without warning would be a very bad thing. You are in control of what happens after you use header. Either exiting or doing other things.

The best example of multiple uses of header that I can think of is when you want to deliver a file for download. It takes a sequence of header calls to properly tell the browser what is going on as illustrated below. If the use of header killed things automatically this, obviously, would not work.

header("Expires: Mon, 26 Jul 1997 05:00:00 GMT");
header("Content-disposition: attachment; filename=test.txt");
header("Content-type: application/octetstream");
header("Pragma: no-cache");
header("Expires: 0");

01-28-2010, 12:36 PM
Exactly Dave. What I like to do fumigator is a simple redirect function

function redirect($url) {
header('Location: '.$url);
}This way it makes it as simple as redirect('http://www.google.com'); and you know it will redirect there immediately. It also means you won't forget to add the exit() like your original problem, as is easy to do in these situations