Lets say, the code looks something like this:
if(!$test) {
header("Location: somefile.html");
...some PHP code....
header("Location: anotherfile.html");
}
Is 'some PHP code' above executed? If yes, then what happens to further HTTP response(s) therein (eg.: the second 'header' statement in the code)?
Yes - the code will be executed.
The header()
will configure the headers to be returned, not send them right away.
If there is no output between the 2
calls, then only the last one will be
taken into account.
However, if you output anything
before the second call, then the
headers will be sent, and the second
call will result in an error (headers
already sent).
A classic mistake is : redirect and not exit()
right after that, which can cause security problems.
the rule is when doing a header redirect put an exit
right after:
if(!$test) {
header("Location: somefile.html");
exit;
//wont ever run
...some PHP code....
header("Location: anotherfile.html");
}
if you don't put the exit
there is a chance that code following might run.
Yes, 'some PHP code' will run. The Location
header is just like any other header. It can only be sent if the script is done executing. Thus, any code in between, assuming there is no exit, has to be run before the header matters.
some other code is executed.
header("Location: xxx");
doesnt stop execution of the code. and it might take some time for the browser to respond.
header("Location: http://www.google.com");
$test = "Hi!";
header("Location: http://www.yahoo.com?t=" . $test);
This code takes my browser to: http://www.yahoo.com/?t=Hi!
The code after header("location")
is executed. You should use an exit();
if you don't want that :)
The redirection IS performed directly by the way, so you probably won't see the effect of things below the first header.