PHP Error Handling

Error handling in PHP is quite simple. The error handling methods used include:

Using the die() function

The first example involves a script that attempts to open a text file. Using a text editor, create a file that contains the following code, and save it to your "htdocs" directory as "error_1.php".

<?php
if(!file_exists("welcome.txt"))
  {
    die("File not found");
  }
else
  {
    $file=fopen("welcome.txt","r");
  }
?>

Start the XAMPP server, and type following URL in your browser address bar:

http://localhost/error_1.php

Assuming the file does not exist, you get the following error message:

File not found

This reports the error, but also stops the script from running. This is not always desirable.

Creating a custom error handler

Creating a custom error handler is not difficult. It involves the creation of a PHP function that can be called each time an error occurs. The function should be able to handle at least two parameters (error level and error message) but may optionally accept three additional parameters (file, line-number, and error context). A brief description of each parameter is given in the table below.


Parameters for PHP Error Handling function
ParameterDescription
error_levelMandatory - specifies the error report level for the user-defined error.
Must be a value number.
See table below for possible error report levels
error_messageMandatory - specifies the error message to be used for the
user-defined error
error_fileOptional - specifies the file in which the error occurred
error_lineOptional - specifies the line number at which the error occurred
error_contextOptional - specifies an array containing the variables (and their
values) that were in use when the error occurred

The error report level determines what type of error the user-defined error handler can be used for:



Error Levels
ValueConstantDescription
2E_WARNINGNon-fatal run-time error - script execution continues
8E_NOTICERun-time notice - may or may not be an error
256E_USER_ERRORFatal user-generated error - execution is halted
512E_USER_WARNINGNon-fatal user-generated warning - execution continues
1024E_USER_NOTICEUser-generated notice - may or may not be an error
4096E_RECOVERABLE_ERRORCatchable fatal error (can be caught by a user-defined handler)
8191E_ALLAll errors and warnings (except level E_STRICT)

The following simple function can be used to handle errors:

function customError($errno, $errstr)
{
  echo "<b>Error:</b> [$errno] $errstr<br>";
  echo "Terminating script";
  die();
}

When invoked, the function gets the error level and an error message, outputs the error level and message, and terminates the script. By default, the built-in PHP error handler is used, but we can override that for a given script by specifying the use of a different error handler using the set_error_handler() function. The following example script uses a similar user-defined function to the one shown above. Note that, because the user-defined function will handle all errors, the set_error_handler() function only requires a single parameter (the name of the user-defined error handler function). Otherwise, a second parameter could be used to specify an error level.

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

//set error handler
set_error_handler("customError");

//invoke the error handler
echo($nonvar);
?>

Create a file that contains the code above, save it to your "htdocs" directory as "error_2.php", and open the file. Because the script attempts to output the value of a non-existent variable ($nonvar), the error-handler is triggered and generates the output:

Error: [8] Undefined variable: nonvar

Triggering an error

If users input invalid data, an error can be triggered using the trigger_error() function. An error can be triggered from anywhere within a script (the error level triggered can be specified by using a second parameter). In the following example script, an E-USER_WARNING is generated if the value of the variable $myvar exceeds 1, causing the custom error handler to be invoked, and terminating the script.

<?php
//error handler
function customError($errno, $errstr)
{
  echo "<b>Error:</b> [$errno] $errstr<br>";
  echo "Terminating script";
  die();
}

//set error handler
set_error_handler("customError",E_USER_WARNING);

//trigger error
$myvar=2;
if ($myvar>1)
{
  trigger_error("Value must be 1 or less", E_USER_WARNING);
}
?>

Create a file that contains the code above, save it to your "htdocs" directory as "error_3.php", and open the file. The output from the above script should be something like this:

Error: [512] Value must be 1 or less
Terminating script

By default an error is recorded in the web server log file (although the action taken can vary, depending on the parameters specified in the php.ini file. The error_log() function can be used, however, to record errors in a specified file. In the following script, errors are sent to the file "myerrors.log", in the "logs" subdirectory of "htdocs".

<?php
//error handler
function customError($errno, $errstr)
{
  echo "<b>Error:</b> [$errno] $errstr<br>";
  echo "The error has been logged.";
  error_log(date (DATE_RSS)." Error: [$errno]
    $errstr".chr(13).chr(10),3, "logs\myerrors.log");
}

//set error handler
set_error_handler("customError",E_USER_WARNING);

//trigger error
$myvar=2;
if ($myvar>1)
{
  trigger_error("Value must be 1 or less\n", E_USER_WARNING);
}
?>

In your "htdocs" directory, create a subdirectory called "logs", and create an empty text file in this subdirectory (using Notepad) called "myerrors.log". Then, create a file that contains the code above, save it to your "htdocs" directory as "error_4.php", and open the file. Refresh the file several times, then open the "myerrors.log" file to see the result. The contents of the file should look something like this:

Wed, 04 Sep 2013 06:19:28 +0200 Error: [512]
    Value must be 1 or less
Wed, 04 Sep 2013 06:20:03 +0200 Error: [512]
    Value must be 1 or less
Wed, 04 Sep 2013 06:20:04 +0200 Error: [512]
    Value must be 1 or less
Wed, 04 Sep 2013 06:20:05 +0200 Error: [512]
    Value must be 1 or less