#native_company# #native_desc#

Building an Error-Handling Mechanism

By PHP Builder Staff
on September 9, 2009

I have found that most developers are really unaware of the
power of error handling in PHP. Some developers I have
talked with recently, simply set error_reporting to 0 and
carry on regardless. If you cannot see the error, it doesnt
exist, right?
Error reporting is there for a reason and should be used for
the purpose it was built. However, we do not want glaring
errors popping up in production website or application–
these could not only be embarrassing, they could be security
flaws. So what is it that we can do to stop errors from
first giving out sensitive server information, and second
killing our script half-way down the page? Luckily for us
PHP has several built-in error handlers for us to use. Let’s
have a look.
Errors Or Die
Let us look at a simple script that opens a text file:


If the file does not exist you might get an error like this:

Warning: fopen(example.txt) [function.fopen]: failed to open stream:

No such file or directory in C:directoryfile.php on line 2

To avoid that, the user gets an error message like the one
above, we test if the file exists before we try to access


die("File not found");

Now if the file does not exist you get an error like this:

File not found

The code above is more efficient than the earlier code,
because it uses a simple error handling mechanism to stop
the script after the error. However, simply stopping the
script is not always the right way to go. Let’s take a look
at alternative PHP functions for handling errors.
Custom Error Handlers
Creating a custom error handler is quite simple. We simply
create a special function that can be called when an error
occurs in PHP.
This function must be able to handle a minimum of two
parameters (error level and error message) but can accept up
to five parameters (optionally: file, line-number, and the
error context):

error_function(error_level, error_message, error_file, 
error_line, error_context) 
error_level: Required. Specifies the error report
level for the user-defined error. Must be a value number.
error_message: Required. Specifies the error message for the user-defined error
error_file: Optional. Specifies the filename in which the error occurred
error_line: Optional. Specifies the line number in which the error occurred
error_context: Optional. Specifies an array containing every variable, and their values, in use when the error occurred