Reputation:
As the title states: why are people calling the exit()
method after a header("...")
while that method is unreachable anyways? Or is it reachable and is it important to add it?
Example:
header("location: $url");
exit();
Upvotes: 2
Views: 82
Reputation: 76646
The header()
call does not stop the execution of your script immediately. If you redirect but you don't call exit()
, then the code is always executed.
To demonstrate this issue, you can consider the following code:
header('Location: http://google.com');
file_put_contents('file.txt', 'I was executed, YAY!');
It will redirect you to Google, but will also output the text in file.txt
. It proves that header()
calls don't necessarily stop the script execution. You should always use exit()
to make sure that the script isn't executed further.
Upvotes: 0
Reputation: 1790
Because header
sends an HTTP header but does not stop the execution of the application, but exit
is actually telling the PHP interpreter to exit the application, so it's a bit of a race condition. If you told the application to wait about 5 seconds before calling exit
it would most likely not execute, depending on the speed of the browser to respond to the HTTP header.
Upvotes: 0
Reputation:
The header()
function does not terminate your application. Any code which follows a header()
call, even to header("Location: …")
, is still executed; its output just happens to be invisible to a web browser. As such, calling exit()
following a redirect is definitely necessary.
Upvotes: 0
Reputation: 13725
The php interpreter only sends a header to the browser when process the header()
command. It means it sends the Location:...
to the browser but continues to process the php file.
So you need the exit()
to stop processing the remaining file.
Upvotes: 2