3

I have a confusion in using PHP header location. which way is best practice...?

if(true){
    header("location:somepage.php");
}

or

if(true){
    header("location:somepage.php");
    exit;
}  
Ravi MCA
  • 2,315
  • 2
  • 17
  • 26

7 Answers7

3

After sending the `Location:' header PHP will continue parsing, and all code below the header() call will still be executed. So instead use your second example:

if(true){
       header("location:somepage.php");
       exit;
  }
Daan
  • 11,690
  • 6
  • 30
  • 49
  • Even tho best practice is properly writing the headers: `header("Location: somepage.php");` – Daniel W. Jun 02 '14 at 11:18
  • If the PHP code ends immediately after, there is no need to `exit()` see (https://stackoverflow.com/questions/8665985/php-utilizing-exit-or-die-after-headerlocation/23061178#23061178). – Leo Jun 18 '16 at 15:24
2

Headers will continue to be sent after an initial header is sent - so if you really, really mean it - you can end the script with an exit;.

The catch however is that you might still want to execute script after the user is redirected to another page - so you don't actually want to put in an exit;.

Example of good code:

header("location:somepage.php");
//continue code and do stuff.

Example of bad code:

header("location:somepage.php");
// Continue code and do other stuff... then...
header("location:somepageOtherPage.php");
// This is the header that the user will get.
Fluffeh
  • 32,630
  • 16
  • 65
  • 80
0

Definitely I would go with the 2nd Option. Otherwise the script execution is not terminated. Setting another header alone is not enough to redirect.

user3669523
  • 69
  • 2
  • 3
  • 11
0

it depends what you want to do: if you want the rest of script to still run after changing the header - use the first option (without the exit() ). if (more likely) you don't want the script to continue - use the second option (with the exit() )

drizzt13
  • 301
  • 2
  • 8
0

I think that if you do not use "exit" the rest of your script will be executed before the redirect.

Samuil Banti
  • 1,527
  • 12
  • 23
0

header() with exit() statement is a good practice. If you don't write exit() it will execute the some statements after the redirection cause problems. exit() will stop all the further execution.

header("location:somepage.php");
exit;
Hassan Siddique
  • 1,560
  • 14
  • 26
0

The second one is correct because the page will automatically redirected to the page where you specified inside header syntax.So exit is not needed.

prakash
  • 21
  • 5