Introduction
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?
Wrong
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:
<?php
$file=fopen("example.txt","r");
?>
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:\directory\file.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
it:
<?php
if(!file_exists("welcome.txt"))
{
die("File not found");
}
else
{
$file=fopen("welcome.txt","r");
}
?>
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
These error report levels are the different types of error the user-defined error handler can be used for:
E_WARNING(value 2): Non-fatal run-time errors. Execution of the script is not halted
E_NOTICE(value 8): Run-time notices. The script found something that might be an error, but could also happen when running a script normally
E_USER_ERROR(value 256): Fatal user-generated error. This is like an E_ERROR set by the programmer using the PHP function trigger_error()
E_USER_WARNING(value 512): Non-fatal user-generated warning. This is like an E_WARNING set by the programmer using the PHP function trigger_error()
E_USER_NOTICE(value 1024): User-generated notice. This is like an E_NOTICE set by the programmer using the PHP function trigger_error()
E_RECOVERABLE_ERROR(value 4096): Catchable fatal error. This is like an E_ERROR but can be caught by a user defined handle (see also set_error_handler())
E_ALL(value 8191): All errors and warnings, except level E_STRICT (E_STRICT will be part of E_ALL as of PHP 6.0)
Now lets create a function to handle errors:
function customError($errno, $errstr)
{
echo "Error: [$errno] $errstr";
echo "Ending Script";
die();
}
The code above is a simple error handling function. When it
is triggered, it gets the error level and an error message.
It then outputs the error level and message and terminates
the script. Now that we have created an error handling
function we need to decide when it should be triggered.
The default error handler for PHP is the built in error
handler. We are going to make the function above the default
error handler for the duration of the script. It is possible
to change the error handler to apply for only some errors,
that way the script can handle different errors in different
ways. However, in this example we are going to use our
custom error handler for all errors:
set_error_handler("customError");
Since we want our custom function to handle all errors, the
set_error_handler() only needed one parameter,
a second parameter could be added to specify an error level.
Testing the error handler by trying to output variable that does not exist:
<?php
//error handler function
function customError($errno, $errstr)
{
echo "Error: [$errno] $errstr";
}
//set error handler
set_error_handler("customError");
//trigger error
echo($example);
?>
The output of the code above should be something like this:
Custom error: [8] Undefined variable: example
In a script where users can input data it is useful to
trigger errors when an illegal input occurs. In PHP, this is
done by the trigger_error() function.
In this example an error occurs if the "example" variable is larger than 1:
<?php
$example=2;
if ($example > 1)
{
trigger_error("Value must be 1 or below");
}
?>
The output of the code above should be something like
this:
Notice: Value must be 1 or below
in C:\directory\file.php on line 6
An error can be triggered anywhere you wish in a script, and
by adding a second parameter, you can specify what error
level is triggered.
E_USER_ERROR - Fatal user-generated run-time error. Errors that can not be recovered from. Execution of the script is halted
E_USER_WARNING - Non-fatal user-generated run-time warning. Execution of the script is not halted
E_USER_NOTICE - Default. User-generated run-time notice. The script found something that might be an error, but could also happen when running a script normally
In this example an E_USER_WARNING occurs if the "example" variable is greater than 1.
If an E_USER_WARNING occurs we will use our custom error handler and end the script.
<?php
//error handler function
function customError($errno, $errstr)
{
echo "Error: [$errno] $errstr";
echo "Ending Script";
die();
}
//set error handler
set_error_handler("customError",E_USER_WARNING);
//trigger error
$example = 2;
if($test > 1)
{
trigger_error("Value must be 1 or below",E_USER_WARNING); }
?>
The output of the code above should be something like this:
Error: [512] Value must be 1 or below
Ending Script
Now that we have learned to create our own errors and how to
trigger them, lets take a look at error logging.
By default, PHP sends an error log to the servers logging
system or a file, depending on how the error_log
configuration is set in the php.ini file. By using the
error_log() function you can send error logs to
a specified file or a remote destination.
Sending errors messages to yourself by e-mail can be a
good way of getting notified of specific errors.
In the example below we will send an e-mail with an error
message and end the script, if a specific error occurs:
<?php
//error handler function
function customError($errno, $errstr)
{
echo "Error: [$errno] $errstr";
echo "Webmaster has been notified";
error_log("Error: [$errno] $errstr",1,
"here@there.com","From: website@server.com");
}
//set error handler
set_error_handler("customError",E_USER_WARNING);
//trigger error
$example=2;
if($example > 1)
{
trigger_error("Value must be 1 or below",E_USER_WARNING);
}
?>
The output of the code above should be something like
this:
Error: [512] Value must be 1 or below
Webmaster has been notified
And the mail received from the code above looks like this:
ERROR: [512] VALUE MUST BE 1 OR BELOW
Conclusion
Something best remembered is that users do not want to see
your error messages. They are there for the content.
Something important to do is to show them a meaningful
notice should that content not be available to them. Above I
have shown very technical error reporting, but I think you
can find your own balance between what you need to know and
what the user needs to see.
Until next time.
Marc Steven Plotz