check123
check123

Reputation: 2009

PHP: Effect of code after header("Location: abc.html")

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

Upvotes: 7

Views: 3617

Answers (6)

Matthieu Napoli
Matthieu Napoli

Reputation: 49553

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.

Upvotes: 15

Nanne
Nanne

Reputation: 64399

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.

Upvotes: 2

Naftali
Naftali

Reputation: 146302

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.

Upvotes: 3

Jeff Lambert
Jeff Lambert

Reputation: 24661

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!

Upvotes: 2

Tjirp
Tjirp

Reputation: 2455

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.

Upvotes: 2

Tanner Ottinger
Tanner Ottinger

Reputation: 3060

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.

Upvotes: 2

Related Questions