What is the use of the die() Function in PHP?
In PHP, the die( )
function is used to immediately terminate script execution and output a message. It is often used to handle critical errors or to provide custom error messages before stopping the script execution abruptly.
Syntax
die(message);
Features
- The
die()
function halts the execution of the script immediately after its invocation. - It is commonly used for error handling or to provide a custom message before terminating script execution.
- If no message is provided,
die()
outputs a default message indicating “Died”.
Difference Between die() Function and exit() Function
die() | exit() |
---|---|
Alias for exit() function with a message parameter |
Equivalent to die() with no message parameter |
Used to terminate script execution with an optional message | Used to terminate script execution without any message |
Output a message to the browser or console before termination | Terminates script execution without outputting any message |
Example:
$file = fopen("example.txt", "r"); if (!$file) {
// Terminate script execution with custom error message die("Unable to open file."); } // Continue script execution if file is successfully opened
Contact Us