The die() and exit() functions in PHP are used to terminate the current script. Both functions are identical and immediately stop script execution. They are commonly used to display an error message or halt execution when a condition fails.
die() and exit() behave exactly the samedie(message)exit(message)
// Stop execution if the file does not exist
<?php
$filename = "nonexistent_file.txt";
if (!file_exists($filename)) {
die("Error: File does not exist.");
}
echo "This line will not be executed.";
?>
If the file does not exist, the script terminates immediately and displays the error message. Any code written after die() will never run.
// Restrict access based on age condition
<?php
$age = 15;
if ($age < 18) {
exit("Access denied. You must be at least 18 years old.");
}
echo "Welcome to the site!";
?>
If the age condition fails, the script stops and shows an access denied message. Otherwise, execution continues normally.
// Terminate script if database connection fails
<?php
$conn = mysqli_connect("localhost", "root", "", "testdb");
if (!$conn) {
die("Database connection failed: " . mysqli_connect_error());
}
echo "Connected successfully!";
?>
Click the button below to simulate a condition-based script termination:
die() or exit() for critical failuresdie() if the user is not logged inexit() when a required file is missingdie()