PHP Reference ยท Language Constructs and Statements
exit and die
Reference for PHP exit and die: stop the script at once, print a message or set an exit status, how shutdown functions and destructors still run.
exit stops the script immediately. die is an exact alias, so the two behave identically. Both are language constructs, not functions, which is why the parentheses are optional.
You can pass a string, which is printed before the script ends, or an integer from 0 to 254, which becomes the process exit status. Shutdown functions and object destructors still run, and output buffers are flushed.
exit("Stopping here\n"); exit(2);
Try it
Press Run (or Ctrl + Enter) to see the result here.
Program input ยท what you'd type while the program runs
Type the answers before you press Run, one per line. Each time the program reads a line (with fgets(STDIN)), it gets the next line from this box.
Press Run (or Ctrl + Enter) to see the result here.
Program input ยท what you'd type while the program runs
Type the answers before you press Run, one per line. Each time the program reads a line (with fgets(STDIN)), it gets the next line from this box.
Syntax
exit; exit(); exit(string $status); exit(int $status); die(string|int $status = "");
| Name | Description |
|---|---|
$status |
Optional. A string is printed and the status is 0. An integer from 0 to 254 is used as the exit status and nothing is printed. 255 is reserved by PHP. |
Return value: none. The script ends (the construct has the return type never).
Usage notes
dieandexitare the same. Pick one and stay consistent; most code usesexit.- A string status is not an error status.
exit("failed")prints the text but the process still exits with 0. Useexit(1)for failure, and print the message separately (for example toSTDERR). - Integers are not printed.
exit(5)produces no output. - Shutdown functions and destructors run, and open output buffers are flushed. Code after the call does not run, and
finallyblocks do not run for anexitinside atry. - Hard to test and hard to reuse. Calling
exitdeep inside a function makes it impossible to continue or to unit test. Prefer returning a value or throwing an exception and let the top of the program decide. - Web requests. After a
header("Location: ...")redirect, callexitso the rest of the page is not processed. - Not a function. You cannot pass
"exit"as a callback; wrap it in a closure instead. - Typing. A function that always exits can declare the return type
never.
Related
return,throw,try / catch- Lessons: Errors, Command-line PHP