Skip to content
Tutorials Center
My learning

Topics

Lesson 61 of 147 ยท Errors and Exceptions

Errors, Warnings and Notices

Learn how PHP reports problems - error levels, warnings vs notices vs deprecations, error_reporting, display_errors vs log_errors, the @ operator and set_error_handler.

Sooner or later every script hits a problem: a variable that was never set, a file that isn't there, a function called with the wrong kind of value. PHP has two ways of telling you. Errors (warnings, notices, deprecations and fatal errors) are diagnostic messages the engine prints or logs. Exceptions are objects that are thrown and can be caught by your code. PHP 8 moved many old fatal errors into the exception system, but the classic error messages are still everywhere, and you need to read them, control where they go and decide which ones should stop your program.

This lesson covers the error side: what each level means, which problems produce which level in modern PHP, how error_reporting, display_errors and log_errors work together, why the @ operator is a trap, and how to take over error handling with set_error_handler(). The next lesson, Exceptions, covers the other half.

Reading an error message

Every PHP error message has the same four parts:

TEXT
Warning: Undefined variable $total in main.php on line 4
^^^^^^^  ^^^^^^^^^^^^^^^^^^^^^^^^^^^    ^^^^^^^^         ^
level    message                        file             line

The level tells you how serious it is. The message says what went wrong. The file and line say where. On a real server the file is a full path like /var/www/app/src/Cart.php; in our editor your code is saved as main.php.

The most important thing to notice is that a warning does not stop the script. PHP prints the message, makes a guess (an undefined variable is treated as null), and keeps going. Run this and watch where the output continues:

PHP Warnings do not stop the script

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with fgets(STDIN)), it gets the next line from this box.

You get two warnings, Undefined array key "cherry" on line 5 and Undefined variable $total on line 6, and the script still reaches "Still running". The cherry price printed as an empty string and $total + 10 gave 10, because both missing values became null. That "carry on with a guess" behavior is exactly why warnings are dangerous: the program produces wrong results instead of failing. Treat every warning as a bug to fix.

The error levels

Each level has a constant, and each constant is a single bit, so levels can be combined with the bitwise operators |, & and ~. These are the ones you'll meet:

Constant Value Meaning Script continues?
E_ERROR 1 Fatal run-time error (out of memory, time limit) No
E_WARNING 2 Something is wrong, PHP guessed and carried on Yes
E_PARSE 4 Syntax error, the file can't be compiled Nothing runs
E_NOTICE 8 Something might be a mistake Yes
E_DEPRECATED 8192 Works now, will break in a future PHP version Yes
E_USER_ERROR 256 Raised by your code with trigger_error() (deprecated in 8.4) No
E_USER_WARNING 512 Your own warning Yes
E_USER_NOTICE 1024 Your own notice Yes
E_USER_DEPRECATED 16384 Your own deprecation Yes
E_ALL 30719 Every level

There are a few more (E_CORE_* and E_COMPILE_* come from the engine's startup and compiler, E_RECOVERABLE_ERROR is rare in PHP 8). E_STRICT is gone: its checks were folded into the other levels long ago, and the constant itself is deprecated since PHP 8.4. That's why E_ALL is 30719 rather than the 32767 you may see in older articles.

What produces which level in PHP 8

PHP 8 raised the severity of many problems. Undefined variables used to be notices; now they're warnings. Things that used to be warnings, like calling a method on null or dividing by zero, now throw an Error exception. Here is a tour of the most common messages:

PHP A tour of common warnings and deprecations

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with fgets(STDIN)), it gets the next line from this box.

The output shows, in order:

  • Warning: Trying to access array offset on null (line 6)
  • Warning: Undefined property: stdClass::$x (line 7)
  • Warning: Array to string conversion (line 8), and the text prints as Tags: Array
  • Deprecated: strlen(): Passing null to parameter #1 ($string) of type string is deprecated (line 10). Passing null to built-in functions that expect a string or number became a deprecation in PHP 8.1; a future version will turn it into a TypeError.
  • Notice: Check the config file (line 12), raised by trigger_error(), whose default level is E_USER_NOTICE.

Fatal errors and parse errors

A fatal error stops the script on the spot. In PHP 8 most of them are really uncaught exceptions, so the message starts with Fatal error: Uncaught:

TEXT
Fatal error: Uncaught Error: Call to undefined function sendMail() in main.php:3
Stack trace:
#0 {main}
  thrown in main.php on line 3

Because these are Error objects, you can catch them; Exceptions shows how. A few fatal errors are not exceptions and can't be caught at all: running out of memory, exceeding max_execution_time, and a handful of compile-time problems.

A parse error is different again. PHP compiles the whole file before running any of it, so a missing semicolon or bracket means nothing in that file runs, not even the lines above the mistake:

TEXT
PHP Parse error:  syntax error, unexpected token "}" in main.php on line 7

A parse error's line number points to where PHP noticed the problem, which is often the line after the real mistake. If line 7 looks fine, check the end of line 6 for a missing ; or ).

Choosing which levels are reported: error_reporting

The error_reporting setting is a bitmask of the levels PHP should report. Anything not in the mask is ignored silently. You can set it in php.ini or at run time with the error_reporting() function, which returns the previous value:

PHP
error_reporting(E_ALL);                    // everything (recommended)
error_reporting(E_ALL & ~E_DEPRECATED);    // everything except deprecations
error_reporting(E_ERROR | E_WARNING);      // only these two
error_reporting(0);                        // nothing at all (never do this)

Read E_ALL & ~E_DEPRECATED as "all bits, AND NOT the deprecated bit". Our editor runs with E_ALL, which is what you want during development: you see every problem while it's cheap to fix.

PHP Changing error_reporting at run time

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with fgets(STDIN)), it gets the next line from this box.

The first call prints a Deprecated: message; the second doesn't, because both deprecation bits were removed from the mask. The function still runs both times: error_reporting only controls the message, never the behavior. (The mask prints as 30719 and then 6143, which is 30719 minus 8192 minus 16384.)

Hiding deprecations is a short-term measure at best. Each deprecation is a feature that a future PHP version will remove, so silencing them just postpones a broken upgrade. Fix them, or at least log them.

Showing vs logging: display_errors and log_errors

Once PHP decides to report an error, two independent settings say where the message goes:

  • display_errors: print the message into the output (the page or the terminal).
  • log_errors: write the message to the error log. The error_log setting names the log file; if it's empty, messages go to the web server's log or, on the command line, to standard error.

The right combination depends on where the code runs:

INI
; Development (php.ini on your machine)
error_reporting = E_ALL
display_errors = On
log_errors = On

; Production (php.ini on the server)
error_reporting = E_ALL
display_errors = Off
log_errors = On
error_log = /var/log/php/app-errors.log

Notice that production still reports everything; it just doesn't show it. Displaying errors on a live site is a security problem: messages leak file paths, SQL fragments and sometimes data, and they break your HTML. Logging everything means you can still find out what went wrong. The deployment lesson and Secure Coding Checklist come back to these settings.

You can see both channels in action. This demo turns display off, logs to a temporary file, then prints the file:

PHP Logging errors to a file instead of showing them

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with fgets(STDIN)), it gets the next line from this box.

The output has no warning in the middle. Instead the log file holds two lines like these (the timestamp is the current time):

TEXT
[18-Oct-2026 09:15:02 UTC] PHP Warning:  Undefined variable $undefinedTotal in main.php on line 9
[18-Oct-2026 09:15:02 UTC] Payment gateway timed out

The error_log() function writes any message you like to the same log, which makes it a quick way to record events without a logging library. Bigger applications use a PSR-3 logger such as Monolog (see Coding Standards and PSRs), which writes to files, services or chat channels with levels like info and critical.

Raising your own errors with trigger_error

trigger_error($message, $level) raises an error from your code. Only the four E_USER_* levels are allowed. The genuinely useful one today is E_USER_DEPRECATED: libraries use it to warn that a function will disappear, without breaking anyone's code yet.

For actual failures, throw an exception instead. PHP 8.4 deprecated trigger_error() with E_USER_ERROR for this reason; the deprecation message itself says to throw an exception or call exit instead.

The @ operator: silence is not a fix

Putting @ before an expression suppresses any error it reports. It's tempting with functions like file_get_contents(), which emit a warning and return false when a file is missing:

PHP What the @ operator hides

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with fgets(STDIN)), it gets the next line from this box.

The @ hid the warning, but the error still happened: error_get_last() returns it (type 2, message file_get_contents(settings.ini): Failed to open stream: No such file or directory). The second half shows the better habit: check the condition first and handle it on purpose.

Problems with @:

  • It hides every error in the expression, including ones you didn't expect, so real bugs vanish.
  • It's slower, because PHP still builds the error and then discards it.
  • Since PHP 8 it no longer hides fatal errors, so it doesn't make code "safe" anyway.

If you must call a function that only reports failure through a warning, wrap it with an error handler that converts the warning to an exception (shown below and in Custom Exceptions). The file-handling lesson uses that approach.

Taking control: set_error_handler

set_error_handler() installs your own function that PHP calls instead of printing the standard message. The handler receives the level, the message, the file and the line:

PHP A custom error handler

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with fgets(STDIN)), it gets the next line from this box.

The two errors raised while the handler is active come out as [WARNING] Undefined array key "ink" (line 22) and [USER WARNING] Low stock (line 23). After restore_error_handler(), PHP's normal Warning: message is back. Some details matter:

  • Return true to say "handled". Return false and PHP also runs its standard handler, which prints or logs the message as usual.
  • Check error_reporting() first. Your handler is called even for levels that are switched off and for expressions behind @. Inside a @ expression, error_reporting() temporarily returns a reduced mask (4437 in PHP 8), so the & test correctly skips them.
  • handleError(...) is the first-class callable syntax (PHP 8.1); a closure or the string 'handleError' also works.
  • An optional second argument limits the handler to certain levels: set_error_handler($fn, E_WARNING | E_NOTICE).

The most common real-world handler does one thing: it throws an ErrorException, turning every warning into an exception that stops bad data in its tracks. Frameworks such as Laravel and Symfony install exactly that in development. You'll write one in Custom Exceptions and Error Handling Strategy.

What an error handler can't catch

set_error_handler() never sees E_ERROR, E_PARSE, E_CORE_* or E_COMPILE_*. To log those, register a shutdown function: it runs when the script ends for any reason, and error_get_last() tells you whether a fatal error was the cause.

PHP Logging a fatal error at shutdown

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with fgets(STDIN)), it gets the next line from this box.

This example fails on purpose. With the memory limit lowered to 8 MB, str_repeat() asks for about 20 MB and PHP stops with Fatal error: Allowed memory size of 8388608 bytes exhausted (tried to allocate 20000032 bytes). The last line never runs, but the shutdown function still does and reports the error. Error trackers like Sentry use this same hook to capture crashes.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. A script runs echo $count + 1; where $count was never assigned. What happens in PHP 8?

    Undefined variables are warnings in PHP 8. PHP treats the variable as null, so null + 1 is 1, and execution continues. That silent guess is why warnings should be fixed.
  2. 2. What is the recommended production configuration?

    Production should still report everything but never show it to visitors. Messages go to the log, where you can find them without leaking paths or data.
  3. 3. What does error_reporting(E_ALL & ~E_DEPRECATED) do?

    The mask keeps all bits of E_ALL and clears the E_DEPRECATED bit. Deprecated code keeps working; only the message is no longer reported.
  4. 4. Your error handler returns false. What happens?

    Returning true means "handled". Returning false passes the error on to PHP's normal handler.
  5. 5. Which problem can set_error_handler() NOT intercept?

    Memory exhaustion is an E_ERROR fatal error, which bypasses custom error handlers. A shutdown function with error_get_last() can still log it.

Summary

  • PHP reports problems as errors (diagnostic messages) and exceptions (objects you can catch). Each error message shows a level, message, file and line.
  • Warnings, notices and deprecations don't stop the script; PHP guesses (often null) and continues, which leads to wrong results. Fix every one.
  • Common PHP 8 warnings: undefined variable, undefined array key, undefined property, array offset on null, array to string conversion. Passing null to built-in string parameters is deprecated (8.1).
  • Most fatal errors in PHP 8 are uncaught Error exceptions; out-of-memory and time limits are true fatal errors. A parse error prevents the whole file from running.
  • error_reporting is a bitmask of levels to report (E_ALL is 30719 in PHP 8.4+). display_errors shows messages, log_errors + error_log writes them to a log. Production: report all, display off, log on.
  • Avoid @; check conditions first. error_get_last() returns the most recent error.
  • set_error_handler() replaces the standard handler (return true when handled, check error_reporting() first); register_shutdown_function() + error_get_last() catches fatal errors at the end.

Next: Exceptions