Why is the exit() method manually being called while it is unreachable anyways because of header("location: ...")?

StackOverflow https://stackoverflow.com/questions/19687366

Question

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();
Was it helpful?

Solution 2

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.

OTHER TIPS

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.

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.

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.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top