What are the differences between die() and exit() functions in PHP?
I think both have the same functionality, but I doubt there is something different in both... what is it?
What are the differences between die() and exit() functions in PHP?
I think both have the same functionality, but I doubt there is something different in both... what is it?
Here is something that's pretty interesting. Although exit() and die() are equivalent, die() closes the connection. exit() doesn't close the connection.
die():
<?php
header('HTTP/1.1 304 Not Modified');
die();
?>
exit():
<?php
header('HTTP/1.1 304 Not Modified');
exit();
?>
Results:
die():
HTTP/1.1 304 Not Modified
Connection: close
exit():
HTTP/1.1 304 Not Modified
Connection: Keep-Alive
Keep-Alive: timeout=5, max=100
Just incase in need to take this into account for your project.
Functionality-wise they are identical but I use them in the following scenarios to make code readable:
Use die() when there is an error and have to stop the execution.
e.g.
die( 'Oops! Something went wrong' );
Use exit() when there is not an error and have to stop the execution.
e.g.
exit( 'Request has been processed successfully!' );
From what I know when I look at this question here
It said there that "in PHP, there is a distinct difference in Header output. In the examples below I chose to use a different header but for sake of showing the difference between exit() and die() that doesn't matter", and tested (personally)
The result of exit() function and die() function is allways same. But as explained in alias manual page (http://php.net/manual/en/aliases.php), it says that die() function calls exit function. I think it is hard coded like below:
function die($msg){
exit($msg);
}
This is not a performance issue for small, medium and large projects but if project has billions multiply billions multiply billions processes, this happens very important performance optimization state.
But very most of people don't thinks this is a problem, because if you have that much processes, you must think more problem than if a function is master or alias.
But, exact answer is that; allways master function is more faster than alias.
Finally; Alias manual page says that, you may no longer use die. It is only an alias, and it is deprecated.
It is usually a bad idea to use these kind of aliases, as they may be bound to obsolescence or renaming, which will lead to unportable script. This list is provided to help those who want to upgrade their old scripts to newer syntax.