Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
die() function in PHP
The die() function in PHP prints a message and immediately exits the current script. It's commonly used for error handling when critical operations fail.
Syntax
die(message)
Parameters
message − Optional. The message to display before terminating the script execution.
Return Value
The die() function does not return any value as it terminates the script execution.
Example 1: Basic Usage
Here's a simple example demonstrating die() with a custom message −
<?php
echo "Script started<br>";
die("Script terminated!");
echo "This line will never execute<br>";
?>
Script started Script terminated!
Example 2: Error Handling with File Operations
The die() function is frequently used with file operations for error handling −
<?php
$filename = "nonexistent.txt";
$file = fopen($filename, "r")
or die("Error: Cannot open file '$filename'!");
?>
Example 3: Database Connection Error
Another common use case is handling database connection failures −
<?php
$connection = mysqli_connect("localhost", "user", "password", "database")
or die("Connection failed: " . mysqli_connect_error());
?>
Key Points
die()is an alias of theexit()functionIt can accept either a string message or an integer exit status
Commonly used with the
oroperator for conditional terminationScript execution stops immediately when
die()is called
Conclusion
The die() function is essential for error handling in PHP, allowing you to gracefully terminate scripts with meaningful error messages. Use it when encountering critical failures that prevent further execution.
