PHP Errors — Complete Guide to Error Handling, Types, and Reporting
In this tutorial, you will learn about PHP Errors. We cover key concepts, practical examples, and best practices to help you master this topic.
PHP errors signal problems in code execution, categorized by severity levels from notices (minor) to fatal errors (crash). Proper error handling prevents information leaks and aids debugging.
What You'll Learn
By the end of this tutorial, you'll understand PHP error types, configure error reporting, create custom error handlers, log errors, and implement appropriate error responses for development and production.
Why Error Handling Matters
Unhandled errors crash applications, expose sensitive information in error messages, and create security vulnerabilities. Proper error handling maintains application stability and security.
Real-World Use
A production e-commerce site sets display_errors to off and logs errors to a file. Error details are never shown to users, but developers review logs daily for issues.
PHP Errors Learning Path
flowchart LR
A[File Handling] --> B[Errors]
B --> C[Exceptions]
C --> D[Classes/Objects]
D --> E[Inheritance]
A --> F{You Are Here}
style F fill:#f90,color:#fff
Error Types
<?php
// Notice (minor, script continues)
echo $undefinedVariable; // Notice: Undefined variable
// Warning (more serious, script continues)
include "nonexistent.php"; // Warning: file not found
// Fatal Error (script stops)
undefinedFunction(); // Fatal error: Call to undefined function
// Parse Error (script doesn't run at all)
// echo "Missing semicolon" // Parse error
Error Reporting Configuration
<?php
// Report all errors except notices
error_reporting(E_ALL & ~E_NOTICE);
// Report all errors in development
error_reporting(E_ALL);
ini_set("display_errors", "1");
// Hide errors in production
ini_set("display_errors", "0");
ini_set("log_errors", "1");
ini_set("error_log", "/var/log/php-errors.log");
Custom Error Handler
<?php
set_error_handler(function(int $errno, string $errstr, string $errfile, int $errline): bool {
$log = sprintf("[%s] Error %d: %s in %s:%d\n",
date("Y-m-d H:i:s"), $errno, $errstr, $errfile, $errline);
file_put_contents("errors.log", $log, FILE_APPEND);
if (ini_get("display_errors")) {
echo "<pre>$log</pre>";
}
return true; // Prevent PHP's internal handler
});
Triggering Errors
<?php
function divide(int $a, int $b): float {
if ($b === 0) {
trigger_error("Division by zero", E_USER_WARNING);
return 0.0;
}
return $a / $b;
}
echo divide(10, 0); // Warning: Division by zero
Error Suppression
<?php
// @ suppresses errors for a single expression
$result = @file_get_contents("missing.json");
if ($result === false) {
// Handle error manually
}
Common Mistakes
1. Displaying Errors in Production
Error messages reveal file paths, database schemas, and configuration details. Always disable display_errors in production.
2. Using @ Error Suppression Excessively
The @ operator suppresses errors but also slows execution (it triggers a change in error reporting level). Fix the root cause instead.
3. Not Checking Function Return Values
Functions like fopen, file_get_contents, and json_decode return false on failure. Always check before using the result.
4. Relying on PHP Default Error Settings
Default settings may not log errors. Configure error_log explicitly for production monitoring.
5. Confusing Warnings and Fatal Errors
Warnings let the script continue (but indicate bugs). Fatal errors stop execution. Handle both appropriately.
Practice Questions
1. What is the difference between E_WARNING and E_ERROR?
E_WARNING does not stop execution. E_ERROR (fatal) stops the script immediately.
2. How do you log PHP errors to a file?
Set ini_set('log_errors', 1) and ini_set('error_log', '/path/to/file'). Errors are appended to the specified file.
3. What does the @ operator do?
It suppresses error messages for the expression it precedes. Use sparingly.
4. How do you create a custom error handler?
Use set_error_handler() with a callback function that receives error level, message, file, and line.
5. Challenge: Create an error handler that sends critical errors via email.
<?php
set_error_handler(function(int $errno, string $errstr): bool {
if ($errno === E_USER_ERROR || $errno === E_ERROR) {
$message = "Critical error: $errstr at " . date("Y-m-d H:i:s");
mail("admin@example.com", "PHP Critical Error", $message);
}
return false;
});
FAQ
Mini Project: Error Logger
Build a comprehensive error logger with severity levels and notification.
<?php
class ErrorLogger {
private string $logFile;
public function __construct(string $logFile = "app_errors.log") {
$this->logFile = $logFile;
set_error_handler([$this, "handleError"]);
}
public function handleError(int $level, string $message, string $file, int $line): bool {
$entry = sprintf("[%s] Level %d: %s in %s:%d\n",
date("Y-m-d H:i:s"), $level, $message, $file, $line);
file_put_contents($this->logFile, $entry, FILE_APPEND);
return true;
}
}
new ErrorLogger();
trigger_error("Test error", E_USER_WARNING);
What's Next
PHP Exceptions PHP Classes Objects PHP Inheritance
Built by the developers of DodaTech
Doda Browser, DodaZIP & Durga Antivirus Pro