PHP die() function explained with code examples

Posted on Aug 06, 2022

Exit your PHP application using the die() function

Photo from Unsplash

The die() function in PHP is used to terminate the running script.

The function is an alias of the exit() function.

die(string $status = ?): void
// or
die(int $status): void

You can pass a string or an int representing the status code for the script termination.

Here’s an example of running the die() function:

<?php

echo "Good morning!";
die("\nScript has been terminated");

echo "Good evening!";

The output will be as follows:

Good morning!
Script has been terminated

The die() function terminates the script before it runs the second echo function, so the text Good evening! was not printed.

You can also send a status code as follows:

die(1);

You can use the die() function to terminate a file delete or write operation when there’s an error.

Consider the following example:

<?php
// 👇 Terminate the script when the image can't be deleted
unlink("assets/image.jpg") 
or die("The file can't be deleted / not found.");

// 👇 Terminate the script when the file can't be opened
$file = fopen("text.txt", "r") 
or die("Unable to open the file");

Although die() is the same as exit(), die() is usually interpreted as an unhandled error in the code while exit() means the code runs successfully.

Only humans know this semantic difference, while both functions are the same for PHP interpreters.

And that’s how the PHP die() function works! 👍

Level up your programming skills

I'm sending out an occasional email with the latest programming tutorials. Drop your email in the box below and I'll send new stuff straight into your inbox!

No spam. Unsubscribe anytime.