Quick Tip: How to Manage Error Reporting in PHP

Share this article

Quick Tip: How to Manage Error Reporting in PHP

In this quick tip on PHP error reporting, we’ll look at how to use the tools available in PHP to handle errors in a controlled way and thereby save hours of debugging.

PHP is, by definition, an “exception-light” programming language. This means that, while it does have exceptions, it will continue to execute any script regardless of what happens unless a fatal error occurs.

For example:

<?php
  echo $sitepoint;

The code above will return the following message:

Notice: Undefined variable: sitepoint in PHP shell code on line 1

PHP will only throw a notice error, and will happily continue executing. An “exception-heavy” language like Python will throw an error and halt execution.

Because of this behavior, PHP developers must be extra careful when writing their code. Unexpected results in the execution of programs might occur, because notices won’t halt the execution but may impact the correct behavior of the program.

Before we go into how to adjust the error reporting style in PHP, let’s first understand the several levels of PHP error severity.

PHP has three main types of messages: errors, notices, and warnings. These represent the different levels of severity: E_ERROR, E_NOTICE, and E_WARNING.

  • Errors are fatal runtime errors and are usually caused by faults in the code. This will cause PHP to stop executing.

  • Notices are messages caused by code that may or may not cause problems (for example, an undefined variable). These will not cause an execution halt.

  • Warnings are non-fatal errors and the script execution won’t be halted.

Error Logging in PHP

By default, PHP doesn’t log any errors. For that to happen, we have to specifically tell it to start logging by turning on the display_errors variable on the PHP configuration file (the php.ini file).

In this file, we can additionally tell PHP if we also want to log notices and warnings, and where this log should be recorded.

There’s also the possibility to trigger logging from within the code. To do this, we can use the error_log() function. Since error logging isn’t the main focus of this article, more information can be found here.

Changing PHP Error Reporting

We can change the default PHP error reporting behavior by using the error_reporting() function. With this function, we can set the level of errors for the duration of the script. This is done by passing one or more of the predefined error constants to the function.

For example, if we want to see not only errors but also notices we could use this:

<?php
error_Reporting(E_ERROR | E_NOTICE);

With this declaration, the script execution will be halted not only for errors but also for notices.

Suppressing Errors

We can also tell PHP to suppress specific errors by using the error control operator (@). By putting this operator at the beginning of an expression, any error that’s a direct result of that expression is silenced:

<?php
echo @$sitepoint;

This will output the value of $sitepoint if it exists, but it’s going to return a NULL and print nothing (instead of throwing a notice) if it doesn’t.

Be very careful when using this operator, as it will completely hide the error. Not only will the error not be displayed, but it also won’t be sent to the error log.

While it may seem harmless, by using this operator you’ll be masking deeper structural issues within your code and covering up potential errant behaviors.

PHP as an Exception-heavy Language

Finally, PHP can also be used as an “exception-heavy” programming language. Normal PHP errors may be thrown as exceptions by using the ErrorException class that extends the PHP Exception class.

In the following example, a user-defined function called errorhandler() is set as error handler with the set_error_handler() function. It throws an ErrorException when a fatal error occurs because a file isn’t found with the file_get_contents() function:

<?php
function errorHandler($severity, $message, $file, $line) {
   if (!(error_reporting() & $severity)) {
      return;
   }
   throw new ErrorException("Fatal Error:No such file or directory", 0, E_ERROR);
}

set_error_handler("errorHandler");

try {
   $data=file_get_contents("sitepoint.txt");
   echo $data;
} catch (ErrorException $e) {
   echo $e->getMessage();
}

By using this method, we can handle execution errors the way we handle exceptions, wrapping them in a try…catch statement with proper instructions on how to behave in such situations.

Conclusion

Summing up, PHP may handle errors in a very loose fashion. It’s up to us developers to use the available tools to better handle them so we can make the most out of the language. By using this set of tools, we can handle errors in a controlled way, saving hours of debugging this way.

FAQs About Managing Error Reporting in PHP

What is error reporting in PHP?

Error reporting in PHP refers to the process of detecting and handling errors or exceptions that occur during the execution of PHP code. Errors can include syntax errors, runtime errors, and logical errors.

How can I enable error reporting in PHP?

You can enable error reporting in PHP by setting the error_reporting configuration directive in your PHP script or in the php.ini configuration file. You can also use the error_reporting function to change the reporting level dynamically within your code.

How do I handle PHP errors gracefully?

You can handle errors gracefully by using try...catch blocks for exceptions and by using conditional statements to check for error conditions before proceeding with code execution.

What is the PHP trigger_error function?

The trigger_error function is used to generate user-level error messages. You can use this function to create custom error messages and trigger them within your code.

How can I log PHP errors for debugging and analysis?

You can log PHP errors to a file using the error_log function. Additionally, you can configure PHP to log errors to specific files by modifying the error_log directive in your php.ini configuration.

Claudio RibeiroClaudio Ribeiro
View Author

Cláudio Ribeiro is a software developer, traveler, and writer from Lisbon. He's the author of the book An IDE Called Vim. When he is not developing some cool feature at Kununu he is probably backpacking somewhere in the world or messing with some obscure framework.

debuggingerror reportingPHP Quick Tips
Share this article
Read Next
Get the freshest news and resources for developers, designers and digital creators in your inbox each week