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,491
  • 4
  • 20
  • 30

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
  • 12,099
  • 6
  • 34
  • 51
  • 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
  • 33,228
  • 16
  • 67
  • 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
  • 630
  • 6
  • 15
0

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

Samuil Banti
  • 1,735
  • 1
  • 15
  • 26
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,590
  • 14
  • 27
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