← Back to Chapters

PHP die() & exit()

? PHP die() & exit()

⚡ Quick Overview

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.

? Key Concepts

  • die() and exit() behave exactly the same
  • They stop execution immediately
  • They can output a message before stopping
  • Useful for error handling and access control

? Syntax / Theory

  • die(message)
  • exit(message)

? Code Example 1: Using die()

? View Code Example
// 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.";
?>

? Live Output / Explanation

If the file does not exist, the script terminates immediately and displays the error message. Any code written after die() will never run.

? Code Example 2: Using exit()

? View Code Example
// 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!";
?>

? Live Output / Explanation

If the age condition fails, the script stops and shows an access denied message. Otherwise, execution continues normally.

?️ Additional Example: Conditional Die

? View Code Example
// 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!";
?>

? Interactive Example

Click the button below to simulate a condition-based script termination:

? Use Cases

  • Stopping execution on missing files
  • Restricting unauthorized access
  • Handling database connection failures
  • Debugging during development

✅ Tips & Best Practices

  • Use die() or exit() for critical failures
  • Always display meaningful messages
  • Avoid overusing them in large applications
  • Combine with proper error handling when possible

? Try It Yourself

  • Create a login check using die() if the user is not logged in
  • Use exit() when a required file is missing
  • Combine form validation with die()