Home » Programming » PHP » Php Exit Die

Using the PHP ‘exit’ (AKA ‘die’) Function to Terminate your Script [Examples]

This short article will explain the PHP exit function and how it is used to quit/exit/terminate a PHP script.

PHP exit Function Syntax

The syntax for the PHP exit function is as follows:

exit(STATUS)

Note that:

  • exit will terminate the execution of the script at the point it is called
  • STATUS is an optional integer or string value containing a status code or exit message
    • If an integer value with a status code, the script will return this code as the exit status if running on the command line
      • Exit status should be 0 for success (i.e., the task completed successfully), or any other integer value up to 255 representing other exit statuses or failures of your own design.
    • If a string value is used as the exit status, it will be printed before exiting.
    • As STATUS is optional, exit can be called without brackets if no status is present.
  • Destructors and shutdown functions will be executed when exit is called

PHP exit Function Examples

The below example demonstrates exiting a script based on a condition and printing an exit message:

$quitNow = true;
if($quitNow){
    exit("The program has been quit")
}

The exit function can be called without brackets if no status is being used:

exit;
exit();
exit("Exiting with a message!");
exit(1); // Exited with an error code

Demonstrating destructors and shutdown functions running after exit is called:

class Bar
{
    public function __destruct()
    {
        echo 'Object of class Foo destructing!';
    }
}

function onShutdown()
{
    echo 'PHP shutting down!';
}

$bar = new Bar();
register_shutdown_function('onShutdown');

exit();

Above, as the shutdown functions and class destructors are called prior to exit completing, the messages for each will be printed.

The PHP die Function

The die function in PHP is identical to the exit function! Simply call

die;

…to exit the script.

SHARE:
Photo of author
Author
I'm Brad, and I'm nearing 20 years of experience with Linux. I've worked in just about every IT role there is before taking the leap into software development. Currently, I'm building desktop and web-based solutions with NodeJS and PHP hosted on Linux infrastructure. Visit my blog or find me on Twitter to see what I'm up to.

Leave a Comment