Skip to content

php_ref_error

Effective error handling is crucial for building robust and maintainable PHP applications. PHP provides mechanisms for reporting errors that occur during script execution and a more structured way to handle exceptional conditions using Exceptions.

Modern PHP development strongly emphasizes using Exceptions for handling recoverable errors and exceptional situations in application logic, while traditional PHP errors (Notices, Warnings, Fatal Errors) signal issues often related to code problems or environment setup.

PHP’s error reporting behavior is controlled by configuration directives, typically set in php.ini, via .htaccess, or directly within scripts using ini_set() and error_reporting().

Name
Default
Description
Changeable
Recommended
`error_reporting`
`E_ALL & ~E_NOTICE & ~E_STRICT & ~E_DEPRECATED` (Older PHP)
`E_ALL` (Modern PHP)
Sets the error reporting level. Use predefined constants (see below). Controls which types of errors are reported.
`PHP_INI_ALL`
**Development:** `E_ALL`
**Production:** `E_ALL` (but log errors, don't display)
`display_errors`
`"1"` (Often overridden to `"0"` in production environments)
Specifies whether errors should be output directly to the browser/console.
`PHP_INI_ALL`
**Development:** `"1"`
**Production:** `"0"` (Security Risk!)
`display_startup_errors`
`"0"`
Controls whether errors occurring during PHP's startup sequence (before script execution begins) are displayed. Keep off unless debugging startup issues.
`PHP_INI_ALL`
**Development:** `"0"` (or `"1"` for debugging)
**Production:** `"0"`
`log_errors`
`"0"`
Defines whether error messages should be logged.
`PHP_INI_ALL`
**Development:** `"1"`
**Production:** `"1"`
`error_log`
*Platform Specific* (e.g., Apache error log, syslog)
Specifies the file or system logger where errors should be logged if `log_errors` is enabled.
`PHP_INI_ALL`
**Development/Production:** Set to a writable file path (e.g., `/var/log/php_errors.log`) or `syslog`.
`log_errors_max_len`
`"1024"`
Sets the maximum length of logged error messages (in bytes). `0` means no limit.
`PHP_INI_ALL`
Usually keep default or increase if needed.
`ignore_repeated_errors`
`"0"`
If `"1"`, ignores repeated messages from the same file/line in the log.
`PHP_INI_ALL`
Keep `"0"` unless logs are excessively noisy.
`ignore_repeated_source`
`"0"`
If `"1"`, ignores repeated messages regardless of source file/line.
`PHP_INI_ALL`
Keep `"0"` generally.
`html_errors`
`"1"`
If `"1"`, formats error messages with HTML tags when `display_errors` is on.
`PHP_INI_ALL`
Irrelevant if `display_errors` is off (production).

Best Practice:

  • Development: Set error_reporting(E_ALL); and ini_set('display_errors', 1); to see all issues immediately.
  • Production: Set error_reporting(E_ALL);, ini_set('display_errors', 0);, ini_set('log_errors', 1);, and configure error_log to write to a secure file or syslog. Never display errors directly to users in production as they can reveal sensitive information.

Exceptions provide an object-oriented way to handle errors and other exceptional conditions. When an exceptional situation occurs, code can throw an exception object. This halts the normal flow of execution and transfers control to the nearest catch block that can handle that type of exception.

try {
// Code that might throw an exception
$result = potentiallyRiskyOperation();
if ($result === false) {
throw new Exception("Operation failed!");
}
echo "Operation successful.";
} catch (SpecificExceptionType $e) {
// Handle specific types of exceptions
echo "Caught SpecificException: " . $e->getMessage();
// Log error, provide user feedback, etc.
} catch (Exception $e) { // Catch any general Exception (or Throwable)
// Handle other exceptions
echo "Caught generic Exception: " . $e->getMessage() . "<br>";
echo "File: " . $e->getFile() . " Line: " . $e->getLine() . "<br>";
// echo "Trace: <pre>" . $e->getTraceAsString() . "</pre>"; // For debugging
} finally {
// Optional block: Code here *always* executes after the try/catch,
// regardless of whether an exception was thrown or caught.
// Useful for cleanup (e.g., closing files or database connections).
echo "<br>Executing finally block.";
}

PHP 7+ introduced the Throwable interface, which both Exception and Error implement. You can catch Throwable to handle almost everything, but it’s often better to catch more specific exception types.

PHP still uses a system of error levels for reporting issues that are not typically handled by try...catch (unless a custom error handler converts them to exceptions).

Error Level Constants (for error_reporting()):

Section titled “Error Level Constants (for error_reporting()):”
Constant
Description
Type
`E_ERROR`
Fatal run-time errors. Script execution stops.
Fatal Error
`E_WARNING`
Run-time warnings (non-fatal). Script execution continues.
Warning
`E_PARSE`
Compile-time parse errors. Generated by the parser, script won't run.
Parse Error
`E_NOTICE`
Run-time notices. Indicates potential issues, but script continues (e.g., using undefined variable).
Notice
`E_CORE_ERROR`
Fatal errors during PHP's initial startup.
Fatal Error
`E_CORE_WARNING`
Warnings during PHP's initial startup.
Warning
`E_COMPILE_ERROR`
Fatal compile-time errors generated by the Zend Engine.
Fatal Error
`E_COMPILE_WARNING`
Compile-time warnings (non-fatal).
Warning
`E_USER_ERROR`
User-generated fatal error message (via `trigger_error()`). Script stops.
User Error
`E_USER_WARNING`
User-generated warning message (via `trigger_error()`). Script continues.
User Warning
`E_USER_NOTICE`
User-generated notice message (via `trigger_error()`). Script continues.
User Notice
`E_STRICT`
Suggests changes for code compatibility/interoperability (Included in `E_ALL` since PHP 5.4).
Strict Standards
`E_RECOVERABLE_ERROR`
Catchable fatal error (e.g., type hint mismatch). Can be caught by error handler.
Catchable Fatal Error
`E_DEPRECATED`
Run-time notices about code that will be removed in future PHP versions.
Deprecated
`E_USER_DEPRECATED`
User-generated deprecated message (via `trigger_error()`).
User Deprecated
`E_ALL`
A combination of all error and warning constants (except `E_STRICT` before PHP 5.4). Recommended for development.
All Errors/Warnings
FunctionDescription
error_reporting(?int $level = null)Sets or gets the current error reporting level.
ini_set(string $option, string|int|bool|null $value)Sets the value of a configuration option (like ‘display_errors’).
trigger_error(string $message, int $error_level = E_USER_NOTICE)Generates a user-level error/warning/notice. Useful for custom library errors.
set_error_handler(?callable $callback, int $error_levels = E_ALL)Sets a custom function to handle PHP errors. Can be used to convert errors into exceptions.
restore_error_handler()Restores the previous error handler function.
set_exception_handler(?callable $callback)Sets a default function to handle uncaught exceptions.
restore_exception_handler()Restores the previous exception handler function.
error_get_last()Returns an associative array describing the last error that occurred (if any).
error_log(string $message, int $message_type = 0, ?string $destination = null, ?string $additional_headers = null)Sends an error message to the configured log, an email address, or a specific file.
debug_backtrace(int $options = DEBUG_BACKTRACE_PROVIDE_OBJECT, int $limit = 0)Generates a PHP backtrace, showing the function call stack.
debug_print_backtrace(int $options = 0, int $limit = 0)Prints a PHP backtrace directly.

Example: Custom Error Handler to Throw Exceptions

Section titled “Example: Custom Error Handler to Throw Exceptions”
<?php
// Set error reporting to maximum
error_reporting(E_ALL);
// Custom error handler function
set_error_handler(function ($severity, $message, $file, $line) {
// Respect error_reporting level
if (!(error_reporting() & $severity)) {
return false; // Error reporting is turned off for this severity level
}
// Throw an ErrorException for PHP errors
throw new ErrorException($message, 0, $severity, $file, $line);
});
try {
echo $undefinedVariable; // This will trigger a Notice, now converted to ErrorException
// Example of triggering a user warning
trigger_error("This is a custom warning", E_USER_WARNING);
} catch (ErrorException $e) {
echo "Caught ErrorException (from PHP error):<br>";
echo "Severity: " . $e->getSeverity() . "<br>";
echo "Message: " . htmlspecialchars($e->getMessage()) . "<br>";
echo "File: " . htmlspecialchars($e->getFile()) . " Line: " . $e->getLine() . "<br>";
// Log the error here in a real application
} catch (Exception $e) {
echo "Caught generic Exception: " . htmlspecialchars($e->getMessage());
}
// Restore the default error handler (optional)
// restore_error_handler();
echo "<br>Script execution continues after catching the error.";
?>

Effective error and exception handling is key to stable applications. Use E_ALL in development, log errors in production, and leverage exceptions for robust control flow.