What are the differences in die() and exit() in PHP?
Asked Answered
R

14

768

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?

Roswald answered 25/11, 2009 at 6:28 Comment(2)
exit() just bails off the program with a numeric exit status, while die() prints out the error message to stderr and exits with EXIT_FAILURE status. so exit() is exit and die() is also exit :)Avouch
I don't want to die, so I use exit.Packet
O
615

There's no difference - they are the same.

PHP Manual for exit:

Note: This language construct is equivalent to die().

PHP Manual for die:

This language construct is equivalent to exit().

Otiose answered 25/11, 2009 at 6:30 Comment(17)
aliases allows programmers to use the one which is comfortable with. I remember exit better than die. Some others remember die better than exit.Toodleoo
this (php.net/manual/en/aliases.php) might give some explanation why 2 functions do the same thingOtiose
Even though they do the same thing, I usually reserve die for error related stops and exit for all other scenarios. It just seems to flow better when reading the code.Creamcups
Sorry to revive this, but at least for me... die is far faster to write than exit... I'm starting to use exit because it's more readable to non-PHP-programmers, but die is just faster to type when you're in a hurry. Also, by the way I type, I don't have to change my hands' position to write die.Ascarid
@nextgentech, You are mis-using it. Use exit(0) for success and exit($non_zero) for errors.Substage
@MarekKarbarz, It doesn't. It merely says both "are equally good".Substage
@mauris, It's way better for one function to have just one name. Imagine every PHP function has two names, that would be a complete mess.Substage
@Substage How am I misusing anything? Your statement just ignores that die() even exists.Creamcups
@nextgentech, I'm not saying you need to choose exit over die, or die over exit. I'm saying make up your mind and pick one. Either one is fine, don't mix both in the same codebase unless you're the only one developing / maintaining it.Substage
Personally I use die when printing an error and exit after a controlled stop like after a redirect. This way it's easier to search for error rules in code.Posthorse
@AlejandroIván If you're acutely perceiving speed gains from typing die instead of exit (and I agree, it's there) then you should seriously consider switching to a keyboard layout like Dvorak - I think you'd really appreciate the speedup after the learning curve.Bimetallic
@Substage Thank goodness the only duplicates in PHP are die and exit! Check this page out: php.net/manual/en/aliases.phpUndistinguished
@mtraceur, AlejandroIván did say "by the way I type, I don't have to change my hands' position to write die" which would mean they're probably using either Dvorak or Colemak since qwerty puts i and e in the top rowRedstone
Try to find all four duplicates in encoding. There is utf8_encode(), iconv, UConvertor and multibyte string. But there are more: dates (IntlCalendar, DateTime and date()), password hashing, etc. It's already a big mess.Chick
I just don't like to think about death a lot, so I use exit();Circumspection
This should be the answer: https://mcmap.net/q/53975/-what-are-the-differences-in-die-and-exit-in-phpMicrogram
@Circumspection I guess that's why I use die()Primordium
V
279

DIFFERENCE IN ORIGIN

The difference between die() and exit() in PHP is their origin.


FUNCTIONALLY EQUIVALENT

die() and exit() are equivalent functions.

PHP Manual

PHP Manual for die:

This language construct is equivalent to exit().

PHP Manual for exit:

Note: This language construct is equivalent to die().

PHP Manual for List of Function Aliases:

die is an alias for master function exit()


DIFFERENT IN OTHER LANGUAGES

die() and exit() are different in other languages but in PHP they are identical.

From Yet another PHP rant:

...As a C and Perl coder, I was ready to answer, "Why, exit() just bails off the program with a numeric exit status, while die() prints out the error message to stderr and exits with EXIT_FAILURE status." But then I remembered we're in messy-syntax-land of PHP.

In PHP, exit() and die() are identical.

The designers obviously thought "Hmm, let's borrow exit() from C. And Perl folks probably will like it if we take die() as is from Perl too. Oops! We have two exit functions now! Let's make it so that they both can take a string or integer as an argument and make them identical!"

The end result is that this didn't really make things any "easier", just more confusing. C and Perl coders will continue to use exit() to toss an integer exit value only, and die() to toss an error message and exit with a failure. Newbies and PHP-as-a-first-language people will probably wonder "umm, two exit functions, which one should I use?" The manual doesn't explain why there's exit() and die().

In general, PHP has a lot of weird redundancy like this - it tries to be friendly to people who come from different language backgrounds, but while doing so, it creates confusing redundancy.

Vedic answered 8/1, 2015 at 23:13 Comment(4)
Even though this is about the 100th answer stating that they are equivalent (as also seen in my answer ^^), this really adds some VERY good points. Most of all that they are NOT the same in other languages (thus the confusion in the first place). (+1)Barocchio
@Levit, No, no, you're getting it totally wrong. No one owns names and different languages reuse the same names in nonequal ways. That's fine because we don't need yet another standard way of doing things. The "confusion in the first place" is due to PHP assigning two different names to one function..Substage
@Pacerier: Sure, if you look at it from the point of "who's fault is it", that is absolutely right. Still it is also a fact that they simply mean different things in several languages (which is ok). Looking at it from a neutral perspective, it definately holds true: There is confusion because of the different meanings (even if it is php's fault for creating two equal function aliases). I definately did not want to point a finger at any of those languages, if that was what you understood from my comment ... (great xkcd btw (Y) ^^)Barocchio
Since they are pretty much identical, I use them in different context for readability. Though that readability might only pertain to me. I use die when something went wrong and exit when something went right. The word die sounds more foreboding so it sticks out to me as something went wrong when reading code.Abbotsun
W
63

As stated before, these two commands produce the same parser token.

BUT

There is a small difference, and that is how long it takes the parser to return the token.

I haven't studied the PHP parser, but if it's a long list of functions starting with "d", and a shorter list starting with "e", then there must be a time penalty looking up the function name for functions starting with "e". And there may be other differences due to how the whole function name is checked.

I doubt it will be measurable unless you have a "perfect" environment dedicated to parsing PHP, and a lot of requests with different parameters. But there must be a difference, after all, PHP is an interpreted language.

Wachtel answered 1/11, 2012 at 15:17 Comment(3)
@Timeless, Perfectionists would not say "PHP is an interpreted language". PHP is a language that can either be interpreted or compiled depending on your server setup.Substage
And... "die" is 3 characters long vs 4 for "exit". So it takes 25% less memory and file space! ;)Steato
'"if it's a long list of functions starting with "d", and a shorter list starting with "e", then there must be a time penalty looking up the function name for functions starting with "e"'. Wouldn't you mean that the time penalty would happen when looking up the function starting with d? Usually, the bigger the list, the longer the time to find an item in it.Mandimandible
B
45

PHP manual on die:

die — Equivalent to exit

You can even do die; the same way as exit; - with or without parens.

The only advantage of choosing die() over exit(), might be the time you spare on typing an extra letter ;-)

Barocchio answered 19/2, 2014 at 14:17 Comment(3)
it also make convenience when someone came from other language, were they get of some familiarity in either of the wayGlance
note that if running php interactively (php -a) die;, die();, exit; and exit(); have no effect, while exit (without semicolon) exits interactive mode.Horsewhip
In interactive mode the die()/exit() function still does what is described in its documentation: it outputs a message and terminates the current script. It terminates only the script, not the interpreter. The interpreter does what it usually does when a script ends: shows the prompt and waits for another script or a command. exit without semicolon at the prompt is a command to the interpreter to terminate itself. You can also use quit for the same purpose.Supertax
M
41

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.

Credits: https://mcmap.net/q/55422/-php-utilizing-exit-or-die-after-header-quot-location-quot-duplicate

Microgram answered 2/5, 2018 at 17:9 Comment(3)
Just tested it and exit and die work the same way, they both close connection.Carthusian
You can simply use die; or exit; without parenthesis if you're not gonna print a message.Johnnie
I agree with Edward and notice a difference. I use Twilio in order to make and receive phone call. In one of my PHP script, I read value from a data base. When there is not result I send a voice message to Twilio then call exit. When there is a result the script continue till the end. When the script goes to the end, for Twilio, that's OK. But when I reach the exit() in my database result test, for Twilio, there os an Error 500. I just change the exit() by die() and now, that's OK. So as say Edward, there is "an internal difference".Mylo
A
38

As all the other correct answers says, die and exit 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 use die("Something went wrong."); to "kill" the script.

When I use exit:

header( "Location: http://www.example.com/" ); /* Redirect browser */
/* Make sure that code below does not get executed when we redirect. */
exit; // I would like to end now.

When I use die:

$data = file_get_contents( "file.txt" );
if( $data === false ) {
    die( "Failure." ); // I don't want to end, but I can't continue. Die, script! Die!
}
do_something_important( $data );

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 see die, 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 or exit where it does not fit my conventions...

Agglomerate answered 15/7, 2015 at 14:0 Comment(1)
I like this answer. To all those lamenting how two names cause confusion, use that to your advantage.Resonate
A
20

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!' );

Adelric answered 26/10, 2018 at 6:10 Comment(0)
K
13

This output from https://3v4l.org demonstrates that die and exit are functionally identical. enter image description here

Katsuyama answered 12/6, 2017 at 8:58 Comment(0)
M
11

This page says die is an alies of exit, so they are identical. But also explains that:

there are functions which changed names because of an API cleanup or some other reason and the old names are only kept as aliases for backward compatibility. 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.

So, call me paranoid, but there may be no dieing in the future.

Mickiemickle answered 22/4, 2014 at 4:20 Comment(5)
It also says In some cases there is no preferred name among the multiple ones, is_int() and is_integer() are equally good for example. Looking at the php-src commit history on GitHub, the die() construct has been in PHP at least since 1999 when it was converted into an SVN repository, and probably for as long as the language has existed. It seems absurd to imagine that it will ever be deprecated.Recor
@MarkAmery, While his premises don't lead to his conclusion, the conclusion itself is valid: ~ "Call me paranoid, but there may be no exit in the future. Or there may be no die in the future"Substage
@Substage Quite right. There may be no PHP in the future, so let's all quit this programming gig and become undertakers or tax collectors. Nothing is certain but death and taxes, after all.Recor
@MarkAmery, "No PHP in the future" seems to be over above-average paranoid. History has shown that insanely popular languages don't die off so easily (Fortran!).Substage
Don't be paranoid. exit will never die. :)Jovial
F
7

They are essentially the same, though this article suggest otherwise.

Flotilla answered 25/11, 2009 at 6:32 Comment(2)
That article is just weird; from the scanner definition you can tell they are equivalent; if there's any difference, perhaps the test was run without an opcache.Aureole
The article is about a benchmark that can't be reproduced as the code is not published. Just ignore it.Jovial
M
1

die() is faster to type than exit();

Millham answered 14/11, 2022 at 3:17 Comment(1)
If only I hadn't run out of dv's today. :(Impacted
W
0

Functionally, they are identical. So to choose which one to use is totally a personal preference. Semantically in English, they are different. Die sounds negative. When I have a function which returns JSON data to the client and terminate the program, it can be awful if I call this function jsonDie(), and it is more appropriate to call it jsonExit(). For that reason, I always use exit instead of die.

Windstorm answered 20/6, 2016 at 15:45 Comment(4)
The OP is asking about PHP exit and die functions only.Galegalea
Yes, and I was answering that question only. To be aware however, the question is not about the difference in functionality only.Windstorm
One of the most lovely functions of mine is called pd() - Which means Please Die. So I'm not sure that die is a bad thing in such a context :)Juetta
As a full stack developer, I am not only seeing myself as a programmer, but also a User Experience designer. And in this context, sympathy is important. Sympathy not only affects how I design UI, but also how I code.Windstorm
D
0

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)

Diaspore answered 31/7, 2018 at 4:54 Comment(0)
D
0

Yes, they are identical twins

But some developers by convention use die when something went wrong and exit when the script must stop but everything is fine

Diocesan answered 7/5, 2023 at 13:2 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.