PHP: Effect of code after header(“Location: abc.ht

2019-04-25 11:34发布

问题:

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)?

回答1:

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.



回答2:

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.



回答3:

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.



回答4:

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.



回答5:

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!



回答6:

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.



标签: php http