How to Use die and exit in PHP: Simple Guide
In PHP,
die() and exit() are language constructs used to stop script execution immediately. Both can output a message before stopping, and they work identically, so you can use either to end your script when needed.Syntax
The basic syntax for die() and exit() is simple. You can call them with or without a message. If you provide a string, it will be printed before the script stops. If you provide an integer, it will be used as the exit status code.
- die(string|int): Outputs a message or sets exit status, then stops the script.
- exit(string|int): Same as
die(), stops the script immediately.
php
die(string|int $status = 0) exit(string|int $status = 0)
Example
This example shows how die() and exit() stop the script and output a message. The script stops at the first call, so the second call won't run.
php
<?php // Using die() to stop script with a message if (!file_exists('important_file.txt')) { die('Error: File not found. Stopping script.'); } // This line will not run if the file is missing exit('This message will not show if die() was called.'); // If the file exists, script continues echo 'File found, continuing script.'; ?>
Output
Error: File not found. Stopping script.
Common Pitfalls
One common mistake is expecting code after die() or exit() to run. These functions stop the script immediately, so any code after them will be ignored. Another pitfall is using them without a message, which can make debugging harder.
Also, using die() or exit() inside included files can stop the whole script unexpectedly.
php
<?php // Wrong: code after die() will not run die('Stop here'); echo 'This will never print'; // Right: place die() only when you want to stop $userLoggedIn = false; if (!$userLoggedIn) { die('Access denied'); } echo 'User is logged in';
Output
Stop here
Quick Reference
| Function | Purpose | Message Output | Stops Script |
|---|---|---|---|
| die() | Stop script execution | Yes (string or int) | Yes |
| exit() | Stop script execution | Yes (string or int) | Yes |
Key Takeaways
Use die() or exit() to immediately stop PHP script execution.
Both functions can output a message before stopping the script.
Code after die() or exit() will not run, so place them carefully.
Providing a message helps with debugging and user feedback.
die() and exit() are interchangeable and work the same way.