PHP Error Handling
Managing and handling errors in PHP applications
⚠️ What is PHP Error Handling?
PHP Error Handling helps you detect, report, and manage errors in your code. It includes built-in error reporting levels, custom error handlers, and logging mechanisms to debug and maintain stable applications effectively.
<?php
// Display all errors
error_reporting(E_ALL);
ini_set('display_errors', 1);
echo "Error handling enabled!";
?>
Output:
Error handling enabled!
Error Types
E_ERROR
Fatal runtime errors
<?php
// Fatal error example
require('missing.php');
?>
E_WARNING
Non-fatal runtime warnings
<?php
// Warning example
include('missing.php');
?>
E_NOTICE
Minor runtime notices
<?php
// Notice example
echo $undefined_var;
?>
E_PARSE
Compile-time parse errors
<?php
// Parse error example
echo "Missing semicolon"
?>
🔹 Setting Error Reporting
Control which errors PHP reports using error_reporting(). This function sets the error reporting level for your script. Use E_ALL during development to catch all issues, and adjust for production to hide sensitive error details from users.
<?php
// Report all errors
error_reporting(E_ALL);
// Report only errors and warnings
error_reporting(E_ERROR | E_WARNING);
// Turn off error reporting
error_reporting(0);
echo "Error reporting configured!";
?>
Output:
Error reporting configured!
🔹 Displaying Errors
The display_errors directive controls whether errors are shown to users. Enable it during development for debugging, but disable it in production to prevent exposing sensitive information. Use ini_set() to change this setting at runtime.
<?php
// Show errors on screen
ini_set('display_errors', 1);
// Hide errors from screen
ini_set('display_errors', 0);
// Log errors to file instead
ini_set('log_errors', 1);
ini_set('error_log', '/path/to/error.log');
?>
Output:
Error display settings configured!
🔹 Custom Error Handler
Create custom error handlers with set_error_handler() to control how errors are processed. This allows you to format error messages, log them to databases, send email alerts, or display user-friendly messages instead of default PHP errors.
<?php
// Define custom error handler
function customError($errno, $errstr) {
echo "Error [$errno]: $errstr";
}
// Set custom handler
set_error_handler("customError");
// Trigger an error
echo $undefined;
?>
Output:
Error [8]: Undefined variable: undefined
🔹 Error Logging
Use error_log() to write error messages to log files or send them via email. This is essential for production environments where you need to track errors without displaying them to users, helping maintain security while monitoring application health.
<?php
// Log error to file
error_log("This is an error message", 3, "errors.log");
// Log with timestamp
$message = date("Y-m-d H:i:s") . " - Error occurred\n";
error_log($message, 3, "errors.log");
echo "Error logged successfully!";
?>
Output:
Error logged successfully!
🔹 Die and Exit
The die() and exit() functions immediately terminate script execution. Use them to stop processing when critical errors occur, preventing further code execution that might cause additional problems or security issues in your application.
<?php
// Check database connection
$conn = mysqli_connect("localhost", "user", "pass");
if(!$conn) {
die("Connection failed: " . mysqli_connect_error());
}
echo "Connected successfully!";
?>
Output:
Connection failed: Access denied for user
🔹 Trigger Custom Errors
Use trigger_error() to generate user-defined error messages at different severity levels. This helps you create meaningful error messages specific to your application logic, making debugging easier and providing better context for error conditions.
<?php
// Trigger custom error
$age = 15;
if($age < 18) {
trigger_error("Age must be 18 or older", E_USER_WARNING);
}
echo "Age validation complete.";
?>
Output:
Warning: Age must be 18 or older
Age validation complete.