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?
In w3schools Quiz: The die() and exit() functions do the exact same thing? my answer is false. That is incorrect answer. The right answer is true.
Here is the screenshot:
As all the other correct answers says,
die
andexit
are identical/aliases.Although I have a personal convention that when I want to end the execution of a script when it is expected and desired, I use
exit;
. And when I need to end the execution due to some problems (couldn't connect to db, can't write to file etc.), I usedie("Something went wrong.");
to "kill" the script.When I use exit:
When I use die:
This way, when I see
exit
at some point in my code, I know that at this point I want to exit because the logic ends here. When I seedie
, I know that I'd like to continue execution, but I can't or shouldn't due to error in previous execution.Of course this only works when working on a project alone. When there is more people nobody will prevent them to use
die
orexit
where it does not fit my conventions...Something I have noticed in my scripts at least is that exit() will stop the currently executing script and pass control back to any calling script, while die will stop php in its tracks. I would say that is quite a big difference?
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)
Here is something that's pretty interesting. Although
exit()
anddie()
are equivalent,exit()
closes the connection.die()
doesn't close the connection.exit()
:die()
:Results:
exit()
:die()
:Just incase in need to take this into account for your project.
Credits: https://stackoverflow.com/a/20932511/4357238
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!' );