Reputation: 2631
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;
}
Upvotes: 3
Views: 1943
Reputation: 21
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.
Upvotes: 0
Reputation: 1590
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;
Upvotes: 0
Reputation: 1795
I think that if you do not use "exit" the rest of your script will be executed before the redirect.
Upvotes: 0
Reputation: 649
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() )
Upvotes: 0
Reputation: 69
Definitely I would go with the 2nd Option. Otherwise the script execution is not terminated. Setting another header alone is not enough to redirect.
Upvotes: 0
Reputation: 33522
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.
Upvotes: 2
Reputation: 12246
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;
}
Upvotes: 3