views:

73

answers:

4
$_SESSION["some_value"] = 4;
header("Location: another-file.php");
$_SESSION["some_value"] = 5;

what's the value of $_SESSION["some_value"] ?

+2  A: 

of course 5. You have to add exit() after such a header.

ts
+8  A: 

The value is 5.

You can output a lot more headers than just Location headers with header, most of which you don't want to stop your code execution. If you want to stop code execution, you need to call exit explicitly.

deceze
+2  A: 

The header command doesn't interrupt the flow of your code. Even if that is encountered, your page is still downloaded by the browser, even if it isn't show. Consider 404 pages, which (despite being errors) are still processed by the browser (though they are rendered while redirects are not).

mattbasta
+1  A: 

Once you issue the header, you've started a race between your code and the webserver/browser. Generally, as soon as the browser receives the redirect, it'll close the connection that ran the script and start connecting to the new redirect URL. When the connection's closed, the web server will generally try to kill the script.

You might get lucky and be able to finish off anything else you wanted to do, or your might be unlucky and the script won't even be able to reach the next line after the header() call.

There is the ignore_user_abort() function, which should let your script continue regardless of the connection's status, though.

Marc B
No, it still downloads the entire response, even if it has a location header. That's why you need to call `exit;` after the header if you want it to redirect without executing any more code. If it was random whether or not it executed the remaining code then that wouldn't be a very useful feature, would it?
Tor Valamo
it wouldn't be a feature. it would just be a funny little bug to remind you that browsers work that way. of course, they don't.
sreservoir