PHP Error
When it comes to programming in PHP, encountering errors is simply a part of the process. However, deciphering these error codes can often be a frustrating and
Encountering errors is a normal part of writing PHP. The faster you can read an error and understand what level it is, why PHP raised it, and how to respond, the faster you ship working code. This page explains PHP's error levels (the E_* constants), the difference between errors and exceptions in modern PHP, and a practical workflow for reporting, logging, and handling them.
PHP Error Levels
When PHP detects a problem it raises it at a specific level, identified by an E_* constant. The level tells you how serious the problem is and whether the script keeps running. You combine these constants with error_reporting() and the php.ini error_reporting directive to decide which levels are shown or logged.
| Constant | Halts script? | Meaning |
|---|---|---|
E_ERROR | Yes | Fatal run-time error, e.g. calling an undefined function. |
E_WARNING | No | Run-time warning, e.g. include of a missing file. |
E_PARSE | Yes | Compile-time syntax error; the file never runs. |
E_NOTICE | No | Minor issue, e.g. reading an undefined variable. |
E_DEPRECATED | No | Feature still works but will be removed in a future version. |
E_USER_ERROR / E_USER_WARNING / E_USER_NOTICE | Varies | Levels you raise yourself with trigger_error(). |
E_STRICT | No | Suggestions for forward-compatible code (folded into E_ALL since PHP 7). |
E_ALL | — | Bitmask that enables every level — use this in development. |
These are bitmask constants, so you combine them with the bitwise OR operator (|) and exclude levels with & plus ~:
<?php
// Report everything except notices and deprecations
error_reporting(E_ALL & ~E_NOTICE & ~E_DEPRECATED);Important: Since PHP 8.0 many former warnings and notices were promoted to thrown
Errorexceptions (for example, reading an undefined array key now warns, while calling an undefined method throws anError). Knowing whether a problem is a raised error or a thrown exception decides how you catch it — see below.
Errors vs. Exceptions
PHP has two related-but-separate mechanisms:
- Traditional errors are raised by the engine and routed through
error_reporting,display_errors, and an optional handler set withset_error_handler(). They are not objects you cancatch(unless your handler converts them). - Exceptions are objects that you
throwandcatchwithtry/catchblocks. Since PHP 7, fatal engine problems are also thrown asErrorobjects (such asTypeErrororDivisionByZeroError), and bothExceptionandErrorimplement theThrowableinterface — socatch (\Throwable $e)catches anything catchable.
<?php
try {
// intdiv() throws a DivisionByZeroError on division by zero
echo intdiv(10, 0);
} catch (\Throwable $e) {
echo get_class($e) . ": " . $e->getMessage();
}
// Output: DivisionByZeroError: Division by zeroCommon Causes of PHP Errors
Most errors trace back to a small set of causes:
- Syntax errors — a missing semicolon or mismatched bracket (
E_PARSE). - Undefined symbols — using a variable, constant, function, or array key that does not exist.
- Type mismatches — passing the wrong type to a typed parameter (throws
TypeError). - Deprecated features — functions or syntax slated for removal (
E_DEPRECATED). - Resource limits — exhausting
memory_limitor hittingmax_execution_time. - External failures — a missing file, or a database/API connection that refuses or times out.
- Uncaught exceptions — a
throwwith no matchingcatch, which becomes a fatal error.
<?php
// Reading an undefined variable raises an E_WARNING and yields null
echo $undefined_variable ?? "fallback";
// Output: fallbackThe null-coalescing operator (??) above is the idiomatic way to read a value that might be undefined without triggering a warning.
Configuring Error Reporting
Control which levels surface and where they go. In development, show everything; in production, hide errors from users but log them.
<?php
// Development: show all errors on screen
error_reporting(E_ALL);
ini_set('display_errors', '1');
// Production: hide from users, write to the error log instead
// error_reporting(E_ALL);
// ini_set('display_errors', '0');
// ini_set('log_errors', '1');The equivalent php.ini settings are error_reporting, display_errors, log_errors, and error_log. For programmatic control see error_reporting() and to inspect the most recent error use error_get_last().
Handling Errors in Code
There are three complementary tools:
1. Catch exceptions with try/catch so a recoverable failure does not crash the script:
<?php
function safeDivide(int $a, int $b): float
{
if ($b === 0) {
throw new InvalidArgumentException("Cannot divide by zero");
}
return $a / $b;
}
try {
echo safeDivide(10, 0);
} catch (InvalidArgumentException $e) {
echo "Handled: " . $e->getMessage();
}
// Output: Handled: Cannot divide by zero2. Install a custom error handler with set_error_handler() to convert traditional errors into exceptions or to log them in your own format:
<?php
set_error_handler(function (int $level, string $message, string $file, int $line) {
// Turn a traditional warning/notice into an ErrorException so it can be caught
throw new ErrorException($message, 0, $level, $file, $line);
});
try {
// Reading a missing file raises an E_WARNING, now converted to an exception
$contents = file_get_contents('/no/such/file.txt');
} catch (\Throwable $e) {
echo "Caught: " . $e->getMessage();
}
// Output: Caught: file_get_contents(/no/such/file.txt): Failed to open stream: No such file or directory3. Trigger your own errors with trigger_error() to signal application-level problems through the same pipeline as engine errors.
Best Practices
- Set
display_errorsto0in production — leaked stack traces are a security risk. Uselog_errorsand a configurederror_loginstead. - Develop with
error_reporting(E_ALL)so notices and deprecations surface early. - Prefer
catch (\Throwable $e)at the top level to capture bothExceptionandError. - Never silence problems with the
@operator; fix the cause or handle it explicitly. - Centralize logging with
error_log()so every failure lands in one place.
Conclusion
Reading a PHP error starts with its level and whether it is a raised error or a thrown exception. With error_reporting() tuned per environment, a custom handler that funnels errors into the exception system, and try/catch around code that can fail, you can diagnose problems quickly and keep production resilient. Continue with PHP Exceptions and error_reporting() to go deeper.