Error Handling in PHP Part-I

Introduction

If you’re a developer, I’m sure you’ve experienced an error message in PHP. In fact, you should be quite familiar with the standard error message format such as this one caused by a call to the header() function after output as started:

Warning: Cannot add header information – headers already sent by (output started at /home/zend.com/proc.inc:6) in /home/zend.com/www/modify_account.php on line 41

This is a fairly typical error message — but did you know that this error message could be changed? In fact, not only can the format of the error message be changed, new features and logic (such as sending an e-mail when an error occurs) can also be developed. Today, we’ll explore custom error handling in PHP, and how you can use it to standardize and simplify error handling from within your scripts.

The problem with standard error handling

Error handling in PHP is a fairly straightforward process. PHP will simply send to the browser (or standard output if executing a script from the command line):

  • an error message containing relative information to the error such as the filename of the script, the specific line in the file that caused the error,
  • a (sometimes) helpful message describing the nature of the error

Unfortunately when dealing with scripts that execute through a browser, PHP pays no consideration to any HTML that may have been in the process of outputting to the browser prior to the error. Because of this, error messages cause rather unpredictable and ugly output and HTML formatting when they occur.

Furthermore, if an error message happens to occur within a HTML comment (such as while outputting JavaScript code), the error message may be hidden and it may not be apparent immediately that an error even occurred. Today I’ll construct a better way to handle errors, and show you how it can be used to provide better error reporting.

Custom error handling in PHP

In order to address the problem outlined above, as well as give the developer more flexibility in error handling, PHP supports the ability to route all error messages through a custom error handling function. Furthermore, PHP provides three error types specifically to be used for errors that your script generates during its execution.

Error types in PHP

PHP internally uses eight error types to classify errors that can occur during the execution of a script. PHP also provides three extra error types that can be used by the user to produce user-defined error messages. To begin, you’ll look at the eight standard error types, and then the last three custom error types and how they can be used to deal with errors generated within your scripts.

Standard error types in PHP

As stated above, PHP uses a total of eight separate error types to categorize the errors that occur during the execution of the script. Some errors require the script to stop executing, while others serve as warnings while the script still continues to execute.

In order to properly construct an error handling function in PHP, these eight types of errors and their significance must be understood. Although in total there are eight separate error types, from an error-handling perspective many of them can be handled in the same way. In fact they are really the same error type generated by different aspects of PHP. When appropriate, you will be made aware of any similar error types and how the error should be treated in relation to other error types.

E_NOTICE

The E_NOTICE error type is a non-fatal error caused when PHP encounters something during the execution of the script (such as an attempt to reference an undefined variable) that may indicate an error within the script. This error by default in PHP is not reported, because it may be generated during the normal execution of a script.

E_WARNING

The E_WARNING error type is another non-fatal error caused by problems that the script itself should have prevented (such as passing invalid data types to an internal PHP function). Although these errors will not prevent the execution of the script, they are serious enough to be displayed to the user by default and should not be ignored by the developer.

E_ERROR

The E_ERROR is the first error type that is considered a “fatal” error. E_ERROR type errors indicate a problem that PHP could not recover from and are displayed by default. Furthermore, E_ERROR type errors must terminate execution of the script when encountered.

E_PARSE

The E_PARSE is generated by the PHP parser, and generally means that a syntax error in the script was encountered. This error must be considered fatal and the script must terminate if it occurs.

E_CORE_ERROR

The E_CORE_ERROR error type is identical to the E_ERROR type of error, except the core of PHP rather than a function within PHP generates it. Because of the similarities between E_CORE_ERROR and E_ERROR, it is safe to treat both error types with the same consideration.

E_CORE_WARNING

As with E_CORE_ERROR, E_CORE_WARNING error type’s counterpart is the E_WARNING error type. Again, because of this similarity between the error types it is acceptable to treat both error types with the same consideration.

E_COMPILE_ERROR

The E_COMPILE_ERROR error type is generated by the Zend Engine, and should be considered no different than the E_ERROR or E_CORE_ERROR error types.

E_COMPILE_WARNING

E_COMPILE_WARNING, as with E_COMPILE_ERROR, is generated by the Zend Engine, and has counterparts in E_WARNING and E_CORE_WARNING. It should be considered in the same way as those types.

Custom error types in PHP

Along with the eight internal errors generated by PHP, PHP also provides three custom error types that your script can generate should your script warrants triggering an error. These error types are the only ones that are to be generated by the developers themselves from within their scripts. They are:

E_USER_NOTICE

The E_USER_NOTICE error is designed to reflect the same purpose as the E_NOTICE internal PHP error. It can be used to notify the user of potential problems in the script that are not of a fatal or perhaps even consequential nature. An example of a potential E_USER_NOTICE error would be type mismatches such as treating a string as an Integer when it may not be appropriate.

E_USER_WARNING

The E_USER_WARNING error is the user-defined version of its E_WARNING internal counterpart. It is designated for errors that prevent the script from continuing the execution of the script normally. An example of this is calling a function and passing a string parameter when an array was expected. This type of serious type mismatch (a string cannot be automatically be converted to an array by PHP) prevents the proper execution of the function, but is not incorrect by syntax and therefore should trigger the E_USER_WARNING error.

E_USER_ERROR

The E_USER_ERROR error is the most serious user-defined error message defined by PHP. Like the other two user-defined error messages E_USER_ERROR mirrors the internal error E_ERROR. This error should be triggered in the event the script encounters an execution-critical error requiring the halt of further code execution. An example would be a mathematical operation that would result in the attempted division by zero.

Creating a custom error handler

The process of creating a custom error handling function is fairly straightforward, as we mentioned earlier many of the internal errors within PHP can be safely combined without any harm. The theory of custom error handling involves creating a specialized function defined from within a PHP script that is called every time an error in PHP occurs.

This specialized function must accept a minimum of two parameters (the error number and the error description) but can accept up to five parameters (optionally accepting the file, line number, and context of in which the error occurred). Therefore, our formal definition of an error handler function would be:

function MyErrorHandler($errno, $errstr [,$errfile,

$errline, $errcontext]) {

}

Where the last three parameters $errfile$errline and $errcontext can be excluded. The meaning of these parameters is as follows:

$errno – The integer value representing one of the defined PHP error constants

$errstr – A string containing an error message associated with the error number

$errfile – The filename of the script that caused the error

$errline – The line number in the $errfile where the error occurred

$errcontext – An array containing all of the variables that were in use when the error occurred and their values. For instance, an error occurring inside of a function will have a $errcontext that contains only a list of variable=>value pairs for variables within that function’s scope.

With this in mind, the development of the error handling function should be apparent. In order to determine the type of error we are handling, simply compare $errno to the list of known error values and the act appropriately. But before you look at an actual example of a real error handling function, you need to know the error functions internally defined by PHP.

Internal error handling functions

PHP internally provides a set of functions that allows you to not only override the internal error handling procedures of PHP, but to trigger errors in PHP in the same way that PHP does so internally. I’ll briefly introduce the primary functions in the family and their use below. For formal definitions of the following functions, consult the PHP manual regarding them.

Set_error_handler()

The set_error_handler() function is used to register a function as the method of handling errors within PHP, thereby overriding the internal error handling procedures in PHP.

Restore_error_handler()

This function is used to reregister the previous error handling function as the method of handling errors in PHP. The restored error handler will be the one used prior to the last set_error_handler() function and could be the internal PHP error handler or another user-defined function.

Error_reporting()

The error_reporting() function is used to define what errors will be processed by the error handling mechanism. Note that when developing custom error handling functions, the error_reporting() function will be called in the event of any error regardless of the settings of error_reporting(). It is the developer’s responsibility to use the error_reporting() function within their script to determine of the error needs to be handled or not.

Error_log()

The error_log() function should be used any time the developer desires to log an error in PHP. Through the use of the error_log() function, errors can be logged to the standard log file(s), e-mailed to specific users, or transmitted to a remote debugging location (not availble in PHP4, and only if enabled in PHP3).

Trigger_error()

The trigger_error() function is used to send a error message to the error handler. Please note that trigger_error() can only send errors that are defined in the E_USER family of constants and cannot trigger errors such as E_ERROR or E_NOTICE.