W3docs

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.

ConstantHalts script?Meaning
E_ERRORYesFatal run-time error, e.g. calling an undefined function.
E_WARNINGNoRun-time warning, e.g. include of a missing file.
E_PARSEYesCompile-time syntax error; the file never runs.
E_NOTICENoMinor issue, e.g. reading an undefined variable.
E_DEPRECATEDNoFeature still works but will be removed in a future version.
E_USER_ERROR / E_USER_WARNING / E_USER_NOTICEVariesLevels you raise yourself with trigger_error().
E_STRICTNoSuggestions for forward-compatible code (folded into E_ALL since PHP 7).
E_ALLBitmask 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 Error exceptions (for example, reading an undefined array key now warns, while calling an undefined method throws an Error). 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 with set_error_handler(). They are not objects you can catch (unless your handler converts them).
  • Exceptions are objects that you throw and catch with try/catch blocks. Since PHP 7, fatal engine problems are also thrown as Error objects (such as TypeError or DivisionByZeroError), and both Exception and Error implement the Throwable interface — so catch (\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 zero

Common 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_limit or hitting max_execution_time.
  • External failures — a missing file, or a database/API connection that refuses or times out.
  • Uncaught exceptions — a throw with no matching catch, which becomes a fatal error.
<?php
// Reading an undefined variable raises an E_WARNING and yields null
echo $undefined_variable ?? "fallback";
// Output: fallback

The 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 zero

2. 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 directory

3. Trigger your own errors with trigger_error() to signal application-level problems through the same pipeline as engine errors.

Best Practices

  • Set display_errors to 0 in production — leaked stack traces are a security risk. Use log_errors and a configured error_log instead.
  • Develop with error_reporting(E_ALL) so notices and deprecations surface early.
  • Prefer catch (\Throwable $e) at the top level to capture both Exception and Error.
  • 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.

Practice

Practice
What are the types of errors in PHP as mentioned in the article?
What are the types of errors in PHP as mentioned in the article?
Was this page helpful?