Error handling is the process of catching errors raised by your program and then taking appropriate action. If you don't handle errors, your website might look broken or expose sensitive server information to users.
PHP has several levels of errors. Understanding them helps you debug faster.
| Error Type | Description |
|---|---|
E_ERROR | Fatal Error. Script execution stops immediately (e.g., calling a non-existent function). |
E_WARNING | Non-fatal error. Script continues execution (e.g., including a missing file). |
E_NOTICE | Minor issue. Script continues (e.g., using an undefined variable). |
die()The die() function prints a message and exits the current script. It is often used when a critical resource (like a database or file) is missing.
<?php
if(!file_exists("welcome.txt")) {
die("File not found! Stopping script.");
} else {
$file = fopen("welcome.txt", "r");
}
?>
You can create a custom function to handle errors your way (e.g., logging them to a file or showing a pretty alert).
<?php
// Error handler function
function myErrorHandler($errno, $errstr) {
echo "<b>Error:</b> [$errno] $errstr<br>";
echo "Webmaster has been notified.";
die();
}
// Set error handler
set_error_handler("myErrorHandler");
// Trigger error
echo($test); // Undefined variable triggers the handler
?>
ini_set('display_errors', 0); and log errors to a private file instead.
set_error_handler) cannot catch E_ERROR (Fatal Errors) because the script stops before the handler can run. To catch these, you need Try/Catch blocks.
trigger_error() to manually fire an error when user input doesn't meet your business logic requirements.
die() and exit() are identical for stopping scripts.set_error_handler() for global custom logic.