PHP Error Handling. Everything You Need To Know

Posted by TotalDC

Last time we talked about Magic Constants in PHP. Now lets learn about Error Handling in PHP, because no developer can avoid errors. So in today’s article you will learn what PHP error handling is and how to use it.

Handling Errors

When creating website you most definitely will run into errors and your code will not work as you planned. There are a number of reasons why errors appeared, for example:

  • A user might have entered an invalid value in a form field.
  • A service that the application needs to access might be temporarily unavailable.
  • The file or database record that you were trying to access may not exist.
  • The application might not have permission to write to a file on the disk

These are runtime errors. They occur at the time your code runs. And good application must handle such runtime errors.

Different Error Levels

When your code encounters a problem, PHP triggers an error. Each error is represented by an integer and an associated constant. Here is a list of the common error levels:

Error levelValueDescription
E_ERROR1A fatal run-time error, that can’t be recovered from. The execution of the script is stopped immediately.
E_WARNING2A run-time warning. It is non-fatal and most errors tend to fall into this category. The execution of the script is not stopped.
E_NOTICE8A run-time notice. Indicate that the script encountered something that could possibly an error, although the situation could also occur when running a script normally.
E_USER_ERROR256A fatal user-generated error message. This is like an E_ERROR, except it is generated by the PHP script using the function trigger_error() rather than the PHP engine.
E_USER_WARNING512A non-fatal user-generated warning message. This is like an E_WARNING, except it is generated by the PHP script using the function trigger_error() rather than the PHP. engine
E_USER_NOTICE1024A user-generated notice message. This is like an E_NOTICE, except it is generated by the PHP script using the function trigger_error() rather than the PHP engine.
E_STRICT2048Not strictly an error, but triggered whenever PHP encounters code that could lead to problems or forward incompatibilities
E_ALL8191All errors and warnings, except of E_STRICT prior to PHP 5.4.0.

PHP triggers an error when it encounters a problem with your code and you can trigger errors by yourself to generate more user friendly error messages. Believe me, all websites or applications must have a way to handle errors.

Error Handling Using The die() Function

Here is an example that tries to open a text file for reading only:

<?php
$file = fopen("sample.txt", "r");
?>

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

Warning: fopen(sample.txt) [function.fopen]: failed to open stream: No such file or directory in C:\wamp\www\tutorial\test.php on line 2

Not very user friendly right? This can be simply fixed with die() function:

<?php
if(file_exists("sample.txt")){
    $file = fopen("sample.txt", "r");
} else{
    die("Error: The file you are trying to access does not exist.");
}
?>

Now if you run the code you will get the error message that looks like this:

Error: The file you are trying to access doesn't exist.

Much better right? The die() function used above simply display the custom error message and terminate the current code if ‘sample.txt’ file is not found.

Creating A Custom Error Handler In PHP

You can create your own error handler functions to handle the run-time errors generated by PHP. The custom error handler provides you better control over the errors, it can inspect the error and decide what to do with it. It can display message to the user or log the error into a file or database or send email. It can even attempt to fix the problem, exit execution of your code or ignore the error.

The custom error handler function must be able to handle at least two parameters (errno and errstr), however it can optionally accept an additional three parameters (errfile, errline, and errcontext), as described below:

RequiredThe following parameters are required
errnoSpecifies the level of the error, as an integer. This corresponds to the appropriate error level constant ( E_ERROR, E_WARNING, and so on)
errstrSpecifies the error message as a string
OptionalThe following parameters are optional
errfileSpecifies the filename of the script file in which the error occurred, as a string
errlineSpecifies the line number on which the error occurred, as a string
errcontextSpecifies an array containing all the variables and their values that existed at the time the error occurred. Useful for debugging

Here is an example of a simple custom error handling function. This function, customError() is triggered when an error occurred. It then outputs the details of the error to the browser and stops the execution of the script.

<?php
// Error handler function
function customError($errno, $errstr){
    print "<b>Error:</b> [$errno] $errstr";
}
?>

You need to tell the PHP to use your custom error handler function by calling the built-in set_error_handler() function, passing in the name of the function. Let’s look at the example:

<?php
// Error handler function
function customError($errno, $errstr){
    print "<b>Error:</b> [$errno] $errstr";
}
 
// Set error handler
set_error_handler("customError");
 
// Trigger error
print($test);
?>

Error Logging In PHP

Log Error Messages In A Text File

You can log details of the error to the text file. Here is an example:

<?php
function calcDivision($dividend, $divisor){
    if($divisor == 0){
        trigger_error("calcDivision(): The divisor cannot be zero", E_USER_WARNING);
        return false;
    } else{
        return($dividend / $divisor);
    }
}
function customError($errno, $errstr, $errfile, $errline, $errcontext){
    $message = date("Y-m-d H:i:s - ");
    $message .= "Error: [" . $errno ."], " . "$errstr in $errfile on line $errline, ";
    $message .= "Variables:" . print_r($errcontext, true) . "\r\n";
    
    error_log($message, 3, "logs/app_errors.log");
    die("There was a problem, please try again.");
}
set_error_handler("customError");
print calcDivision(10, 0);
print "This will never be printed.";
?>

Send Error Message By Email

You can also send email with the error details using the same error_log() function. Look at the example:

<?php
function calcDivision($dividend, $divisor){
    if ($divisor == 0){
        trigger_error("calcDivision(): The divisor cannot be zero", E_USER_WARNING);
        return false;
    } else{
        return($dividend / $divisor);
    }
}
function customError($errno, $errstr, $errfile, $errline, $errcontext){
    $message = date("Y-m-d H:i:s - ");
    $message .= "Error: [" . $errno ."], " . "$errstr in $errfile on line $errline, ";
    $message .= "Variables:" . print_r($errcontext, true) . "\r\n";
    
    error_log($message, 1, "webmaster@example.com");
    die("There was a problem, please try again. Error report submitted to webmaster.");
}
set_error_handler("customError");
print calcDivision(10, 0);
print "This will never be printed.";
?>

Trigger An Error In PHP

Although the PHP triggers an error when it encounters a problem in your code, you can also trigger errors by yourself. This can be helpful when you need to make your application more robust by flagging potential problems before they turn into serious errors.

To trigger an error within your code you have to call the trigger_error() function and pass in the error message that you want to generate:

trigger_error("There was an error.");

Here is a function that calculates division of the two numbers:

<?php
function calcDivision($dividend, $divisor){
    return($dividend / $divisor);
}
 
// Calling the function
print calcDivision(10, 0);
?>

If a value of zero (0) is passed as the $divisor parameter, the error generated by the PHP will look like this:

Warning: Division by zero in C:\wamp\www\tutorial\test.php on line 3

This message doesn’t look very informative. Let’s look at the following example that uses the trigger_error() function to generate the error:

<?php
function calcDivision($dividend, $divisor){
    if($divisor == 0){
        trigger_error("The divisor cannot be zero", E_USER_WARNING);
        return false;
    } else{
        return($dividend / $divisor);
    }
}
 
// Calling the function
print calcDivision(10, 0);
?>

And now you will get error that looks like this:

Warning: The divisor cannot be zero in C:\wamp\www\tutorial\error.php on line 4

Again custom error looks much better that default PHP error.

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.

%d bloggers like this: