Categories
Uncategorized

PHP exit() / die() With Strings

Short Version: Don’t do it!

I recently had a discussion about calling PHP exit() ( which is what die() gets mapped to ) with a string instead of an integer. While the PHP docs indicate that calling it with a string is ok, I submit that is almost never the right thing to do ( like 99.999999999% of the time ).

Here is an example of what I mean:

<?php
exit( 'Something went wrong.' );

Why is this a problem? It sets the exit status to zero. Why is that a problem? Because the common convention is that ( # ):

systems typically use a convention of zero for success and nonzero for error

There is an easy way to see this behavior using the command line:

$ php -r "exit( 'Something went wrong.' );"
Something went wrong.
$ echo $?
0

Even though the text of the message was about a problem, the status code said everything is fine. That is the status code equivalent of:

If you are calling exit() and everything really is fine, make sure the status code you return is zero. For any other type of condition, make sure the exit code is something NOT zero. For example:

$ php -r "exit( 14 );"
$ echo $?
14

The PHP docs indicate that valid status values “should be in the range 0 to 254”. That leaves 1 to 254 for error conditions.

Leave a Reply

Your email address will not be published. Required fields are marked *