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

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

문제

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();
도움이 되었습니까?

해결책 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.

다른 팁

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.

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top