Is there any differences between PHP die() and exit()?

Based on the documentation, the PHP die() function is equal to the exit() function.

There’s no technical difference between the die() and exit() function.

There is only a semantic difference between the die() and exit() function:

  • die() is recommended when you stop PHP script because of an exception
  • exit() is used when your PHP script require something from the user

Here’s an example:

// 👇 Using exit
$name = null;
if (!$name) {
    echo "Please input name";
    exit();
}

// 👇 Using die
$name = null;
if (!$name) {
    die("name variable is empty!");
}

While both exit and die do the same thing, die feels like there’s an error with the program, while exit seems like the program needs something from the user.

And that’s the only difference between die() and exit() function.

The guideline is: use exit() when the user needs to do something. Use die() when some expected data is missing.

Take your skills to the next level ⚡️

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

No spam. Unsubscribe anytime.