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

2019-04-25 10:58发布

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

标签: php http
6条回答
不美不萌又怎样
2楼-- · 2019-04-25 11:38

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.

查看更多
我命由我不由天
3楼-- · 2019-04-25 11:40

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.

查看更多
We Are One
4楼-- · 2019-04-25 11:43

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.

查看更多
Rolldiameter
5楼-- · 2019-04-25 11:54
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楼-- · 2019-04-25 11:56

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.

查看更多
兄弟一词,经得起流年.
7楼-- · 2019-04-25 12:03

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.

查看更多
登录 后发表回答