How to Exit a PHP Script with an Exit Code
Every program ends with an exit code: 0 when it succeeded, anything else when it didn't. Shells, scripts and CI jobs read that number to decide what happens next. A PHP command-line script sets its own with exit(1).
Syntax
exit(<code>);
| Part | What it does |
|---|---|
exit | Stops the script. |
<code> | An int exit code: 0 for success, 1 to 254 for errors. |
The PHP manual for exit: "An exit code of 0 is used to indicate that the program succeeded in its tasks. Any other value indicates some sort of error occurred during execution." It adds: "Exit codes should be in the range 0 to 254, the exit code 255 is reserved by PHP and should not be used."
The Example
The example checks whether all orders are paid. They aren't, so it writes an error and exits with code 1.
Prerequisites
- PHP for the command line. This guide uses PHP 8.6.0.
Step 1: Write the Code
Create a file named main.php:

<?php
$allPaid = false;
if (!$allPaid) {
fwrite(STDERR, "Some orders are not paid.\n");
exit(1);
}
echo "All orders are paid.\n";
Step 2: Run It and Read the Exit Code
Run the script, then ask the shell for the exit code of the last command:
- macOS / Linux
- Windows (PowerShell)
php main.php
echo $?

php main.php
$LASTEXITCODE

Some orders are not paid.
1
The last line of the script never ran, and the shell reported 1.
A String Isn't an Error Code
exit also accepts a string, but then it only prints it. The manual: "If status is a string, this function prints the status just before exiting. The exit code returned by PHP is 0." exit("Goodbye\n") printed Goodbye and ended with code 0, so a CI job would treat it as success. Write the message to STDERR and exit with a number instead.
Common Mistakes
| Mistake | What happens | Do this instead |
|---|---|---|
exit("Something failed") | It prints the text and reports success, 0 | Write the message, then exit(1) |
Expecting a finally block to run | The manual says finally blocks are never executed after exit; one didn't print | Clean up before calling exit |
Using 255 as your own code | PHP reserves it; an uncaught error also exits with 255 | Use 1 to 254 |
Troubleshooting
| Symptom | Likely cause | Fix |
|---|---|---|
echo $? prints 0 after an error | The script ended normally, or exited with a string | Exit with a number |
The exit code is 255 | A fatal error or an uncaught exception ended the script | Read the error above it |
FAQ
What's the difference between exit and die?
None: die is another name for exit.
What code does a fatal error give?
255. Every uncaught error in my checks, from a TypeError to a missing class, ended with code 255.
Conclusion
exit(1) ends a PHP script with a failure code that the shell reads as $? in zsh or bash and $LASTEXITCODE in PowerShell. Pass a number, not a string, and keep to 0 through 254.
Additional Resources
- exit, in the PHP manual.
