$_SESSION["some_value"] = 4;
header("Location: another-file.php");
$_SESSION["some_value"] = 5;
what's the value of $_SESSION["some_value"]
?
$_SESSION["some_value"] = 4;
header("Location: another-file.php");
$_SESSION["some_value"] = 5;
what's the value of $_SESSION["some_value"]
?
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).You should always die() or exit() after the redirect (or as pointed out by Mark B, use ignore_user_abort() ) because you can't otherwise know for certain what will happen.
Though some code will get executed after a header location redirect, it's important to note that not all code after it will necessarily get executed.
As per your example, yes, some_value will equal 5. But at some point the script will get prematurely terminated.
Take the following example:
If all the other answers were correct, you'd assume $_SESSION['some_value'] would equal 'finished!' -- but I ran the code and this is not the case.
Here are my results:
Trial two:
Trial three:
Trial four:
Trial five:
If I implement ignore_user_abort(TRUE); in the above script then some_value does equal "finished!" so keep that in mind if you intend to do something critical like logging or database queries or sending emails after the redirect.
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.of course 5. You have to add exit() after such a header.
The value is 5.
You can output a lot more headers than just
Location
headers withheader
, most of which you don't want to stop your code execution. If you want to stop code execution, you need to callexit
explicitly.