How to Handle Errors in PHP
When building robust PHP applications, proper error handling is essential. It not only helps developers debug issues faster but also prevents sensitive information from leaking to end users. This guide covers everything you need to know—from basic error reporting settings to advanced custom error handlers and exception management.
1. Understanding PHP Error Types
PHP categorizes errors into several levels. Knowing each type helps you decide how to respond.
1.1 Notices
Minor issues that don’t stop script execution, such as accessing an undefined variable.
1.2 Warnings
More serious problems, like including a missing file, but the script continues.
1.3 Fatal Errors
Critical errors that halt script execution, e.g., calling an undefined function.
1.4 Parse Errors
Syntax errors detected during compilation. The script never runs.
2. Configuring Error Reporting
Set the appropriate error reporting level for each environment (development, staging, production).
// Development (show all errors)
ini_set('display_errors', 1);
error_reporting(E_ALL);
// Production (log only, hide from users)
ini_set('display_errors', 0);
error_reporting(E_ALL & ~E_DEPRECATED & ~E_STRICT);
ini_set('log_errors', 1);
ini_set('error_log', __DIR__ . '/logs/php-errors.log');
3. Using try / catch with Exceptions
Since PHP 5, the Exception class provides a modern way to handle errors.
try {
// Code that may throw an exception
$pdo = new PDO($dsn, $user, $pass);
$pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
// ... other DB operations
} catch (PDOException $e) {
// Log the error and show a generic message to the user
error_log($e->getMessage());
echo 'A database error occurred. Please try again later.';
}
4. Creating a Custom Error Handler
For full control, register a custom handler with set_error_handler(). This allows you to convert traditional PHP errors into Exceptions or log them in a structured format.
function myErrorHandler($severity, $message, $file, $line) {
// Convert error to exception if it's not suppressed with @
if (!(error_reporting() & $severity)) {
return;
}
// Build a detailed error message
$logMessage = sprintf(
"[%s] %s in %s on line %d",
date('Y-m-d H:i:s'),
$message,
$file,
$line
);
// Log to file
error_log($logMessage, 3, __DIR__ . '/logs/custom-errors.log');
// Optionally throw an exception for critical errors
if ($severity & (E_ERROR | E_CORE_ERROR | E_COMPILE_ERROR | E_USER_ERROR)) {
throw new ErrorException($message, 0, $severity, $file, $line);
}
// Return true to bypass PHP's internal handler
return true;
}
// Register the handler
set_error_handler('myErrorHandler');
5. Shutdown Functions for Fatal Errors
Fatal errors cannot be caught by set_error_handler(). Use register_shutdown_function() to capture them.
register_shutdown_function(function () {
$error = error_get_last();
if ($error && in_array($error['type'], [E_ERROR, E_CORE_ERROR, E_COMPILE_ERROR, E_PARSE])) {
$msg = sprintf(
"Shutdown error: %s in %s on line %d",
$error['message'],
$error['file'],
$error['line']
);
error_log($msg, 3, __DIR__ . '/logs/shutdown-errors.log');
// Show a generic response to the user
if (!headers_sent()) {
http_response_code(500);
echo 'An unexpected error occurred. Please contact support.';
}
}
});
6. Best Practices for Production
- Never display raw errors to users. Use generic messages and log details securely.
- Centralize logging. Use a library like Monolog to send logs to files, syslog, or external services.
- Separate environments. Keep distinct
php.inior configuration files for development vs. production. - Monitor logs. Set up alerts (e.g., via Slack or email) for critical errors.
- Test error handling. Write unit tests that trigger exceptions and verify your custom handlers work as expected.
7. Quick Checklist
- Set
display_errorsto0in production. - Enable
log_errorsand define a secure log path. - Use
error_reporting(E_ALL)during development. - Implement a global
set_error_handler()to centralize error processing. - Wrap risky code in
try / catchblocks. - Register a shutdown function for fatal errors.
- Regularly review and rotate log files.
Conclusion
Effective error handling in PHP is a blend of proper configuration, strategic use of exceptions, and custom logging. By following the steps outlined above, you’ll create applications that are easier to debug, more secure, and resilient in production environments.
Start implementing these practices today, and watch your PHP projects become more stable and professional.