717

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?

Donald Duck
  • 6,488
  • 18
  • 59
  • 79
coderex
  • 24,487
  • 43
  • 111
  • 167
  • 3
    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 :)` – Muhammad Shahzad Apr 06 '16 at 09:37

15 Answers15

569

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().

Marek Karbarz
  • 27,742
  • 6
  • 49
  • 73
  • 18
    aliases allows programmers to use the one which is comfortable with. I remember exit better than die. Some others remember die better than exit. – mauris Nov 25 '09 at 06:35
  • 31
    this (http://php.net/manual/en/aliases.php) might give some explanation why 2 functions do the same thing – Marek Karbarz Nov 25 '09 at 07:17
  • 93
    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. – nextgentech Jan 11 '14 at 04:29
  • 8
    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`. – Alejandro Iván Feb 27 '15 at 14:17
  • 1
    @nextgentech, You are mis-using it. Use `exit(0)` for success and `exit($non_zero)` for errors. – Pacerier Jun 30 '15 at 05:30
  • @MarekKarbarz, It doesn't. It merely says both "are equally good". – Pacerier Jun 30 '15 at 05:31
  • 7
    @mauris, It's [way better for one function to have just one name](http://stackoverflow.com/a/27851270/632951). Imagine every PHP function has two names, that would be a **complete mess**. – Pacerier Jun 30 '15 at 05:46
  • 1
    @Pacerier How am I misusing anything? Your statement just ignores that `die()` even exists. – nextgentech Jun 30 '15 at 19:43
  • 2
    @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. – Pacerier Jul 02 '15 at 07:51
  • 1
    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. – Gilles Lesire Mar 30 '16 at 09:05
  • @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. – mtraceur Mar 19 '17 at 20:38
  • 2
    @Pacerier Thank goodness the only duplicates in PHP are `die` and `exit`! Check this page out: http://php.net/manual/en/aliases.php – CJ Dennis Dec 03 '17 at 09:37
  • @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 row – 3ocene Dec 04 '18 at 20:34
  • 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**. – Code4R7 Jul 07 '19 at 19:33
  • I just don't like to think about death a lot, so I use exit(); – dan Dec 06 '19 at 20:48
  • 1
    This should be the answer: https://stackoverflow.com/a/50140070/4357238 – Edward Dec 17 '19 at 15:20
240

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.

Geoffrey Hale
  • 8,152
  • 4
  • 34
  • 42
  • 15
    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) – Levite Apr 07 '15 at 06:36
  • @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](https://xkcd.com/927/) standard way of doing things. The "confusion in the first place" is due to PHP assigning [two different names](http://stackoverflow.com/questions/1795025/what-are-the-differences-in-die-and-exit-in-php#comment50272429_1795031) to one function.. – Pacerier Jun 30 '15 at 12:03
  • 2
    @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) ^^) – Levite Jul 01 '15 at 06:24
  • 2
    This should definitely be the chosen answer, good description! – Cody Brown Apr 24 '19 at 18:48
  • Another user answered that `exit()` does not close the connection while `die()` does, seems relevant. – ner0 Dec 16 '19 at 23:13
62

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.

Sayed Mohd Ali
  • 2,004
  • 3
  • 8
  • 25
Bob
  • 840
  • 6
  • 8
  • 4
    @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. – Pacerier Jun 30 '15 at 05:38
  • 30
    And... "die" is 3 characters long vs 4 for "exit". So it takes 25% less memory and file space! ;) – Jan Derk Nov 24 '15 at 21:04
  • 2
    '"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. – Pere Dec 17 '15 at 18:43
  • 13
    As you wrote, you haven't studied the PHP parser. Thanks for this useless answer as it is based on your dreams on how PHP is implemented. – dolmen Jan 24 '18 at 13:09
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 ;-)

Davicus
  • 388
  • 3
  • 14
Levite
  • 15,387
  • 7
  • 47
  • 46
  • 1
    it also make convenience when someone came from other language, were they get of some familiarity in either of the way – Rohan Khude Nov 30 '17 at 08:12
  • note that if running php interactively (`php -a`) `die;`, `die();`, `exit;` and `exit();` have no effect, while `exit` (without semicolon) exits interactive mode. – santiago arizti Dec 11 '19 at 21:22
39

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:

exit():

HTTP/1.1 304 Not Modified 
Connection: Keep-Alive 
Keep-Alive: timeout=5, max=100

die():

HTTP/1.1 304 Not Modified 
Connection: close

Just incase in need to take this into account for your project.

Credits: https://stackoverflow.com/a/20932511/4357238

Edward
  • 2,155
  • 1
  • 14
  • 32
33

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...

Lukas
  • 767
  • 7
  • 13
15

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

aagjalpankaj
  • 892
  • 13
  • 24
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.

Pedram Behroozi
  • 2,017
  • 2
  • 26
  • 41
  • 3
    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. – Mark Amery Nov 30 '14 at 21:53
  • 2
    @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"* – Pacerier Jun 30 '15 at 11:56
  • @Pacerier 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. – Mark Amery Jun 30 '15 at 12:00
  • @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!). – Pacerier Jul 02 '15 at 08:01
  • 2
    Don't be paranoid. *exit* will never *die*. :) – dolmen Jan 24 '18 at 13:24
10

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

Simon77
  • 306
  • 4
  • 3
7

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

o.k.w
  • 24,261
  • 6
  • 60
  • 62
  • 1
    That article is just weird; from the [scanner definition](https://github.com/php/php-src/blob/master/Zend/zend_language_scanner.l#L1011) you can tell they are equivalent; if there's any difference, perhaps the test was run without an opcache. – Ja͢ck Nov 25 '14 at 05:03
  • 2
    The article is about a benchmark that can't be reproduced as the code is not published. Just ignore it. – dolmen Jan 24 '18 at 13:14
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.

Luo Jiong Hui
  • 4,526
  • 2
  • 21
  • 15
  • The OP is asking about PHP exit and die functions only. – Black Mamba Mar 02 '17 at 07:10
  • 1
    Yes, and I was answering that question only. To be aware however, the question is not about the difference in functionality only. – Luo Jiong Hui Mar 02 '17 at 11:16
  • 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 :) – Ivan Ponomarev Jan 06 '18 at 10:35
  • 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. – Luo Jiong Hui Jan 08 '18 at 14:54
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)

-5

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.

MERT DOĞAN
  • 2,022
  • 19
  • 25
  • 2
    Aliasing is not 'calling a function'. Check your assumptions before elaborating hypothesis. – dolmen Jan 24 '18 at 13:18
  • @dolmen Aliases allways calles main functions in hard codes. This is a general programming rule. – MERT DOĞAN Jan 24 '18 at 22:43
  • @MERTDOĞAN An alias doesn't call anything. An alias (in programming or in real life) is just another name of an object (that already has a name). `die()` is not a separate function. It is just another name of `exit()`. This answer contains incorrect statements about aliases and their performance. – axiac Mar 15 '18 at 07:26
  • http://docs.php.net/manual/en/migration56.new-features.php#migration56.new-features.use Aliases allways calles like above example. Learn something and come back. – MERT DOĞAN Mar 16 '18 at 12:04
-7

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?

noowie
  • 29
  • 1
  • 1
  • 7
-10

They sound about the same, however, the exit() also allows you to set the exit code of your PHP script.

Usually you don't really need this, but when writing console PHP scripts, you might want to check with for example Bash if the script completed everything in the right way.

Then you can use exit() and catch that later on. Die() however doesn't support that.

Die() always exists with code 0. So essentially a die() command does the following:

<?php
echo "I am going to die";
exit(0);
?>

Which is the same as:

<?php
die("I am going to die");
?>
Icheb
  • 237
  • 1
  • 1
  • 44
    That's not true. `die` and `exit` are identical (they produce the same parser token (`T_EXIT`) and are executed by the same code). If the parameter is an integer, it will return that code to the shell. If it is not, it will output it and return 0. So `die` and `exit` are literally aliases for each-other. – ircmaxell Apr 29 '11 at 13:25
  • 6
    well if you know you can use exit("I'm exiting..."); – Yuda Prawira Apr 11 '13 at 08:33
  • 4
    23 upvotes so far for an answer that's simply false! This is why I never vote on answers until I've read all the competing answers to the question and understand them all (barring terribly written ones I can't make any sense of). – Mark Amery Dec 01 '14 at 11:31
  • 3
    This is exactly what @GeoffreyHale writes about in his answer. What you posted as answer is what one would expect, coming from a language like Perl or C. But as the others mentioned it is **not** true for php. You might really consider editing your answer to reflect this, or deleting it otherwise. – Levite Apr 07 '15 at 06:43