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 the exit() function

  • It can accept either a string message or an integer exit status

  • Commonly used with the or operator for conditional termination

  • Script 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.

Updated on: 2026-03-15T07:36:04+05:30

3K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements