PHP Error Handling

In PHP, the default error handling is simple. A message is sent to the browser, which includes the filename, line number, and a description of the error.

PHP Error Handling

Error handling is an important part when creating scripts and web applications. If your code lacks error detection coding, the program looks unprofessional and opens the door to security risks.

This tutorial introduces some of the most important error detection methods in PHP.

We will explain different methods of error handling to you:

  • Simple "die()" statement
  • Custom errors and error triggers
  • Error Reporting

Basic error handling: Using the die() function

The first example shows a simple script to open a text file:

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

If the file does not exist, you will get an error similar to this:

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

To avoid the user receiving an error message similar to the one above, we check if the file exists before accessing 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 will get an error message similar to this:

File not found

Compared to the previous code, the code above is more effective because it terminates the script after a simple error handling mechanism.

However, simply terminating the script is not always the appropriate way. Let's look at alternative PHP functions for error handling.

Creating a custom error handler

Creating a custom error handler is very simple. We simply create a dedicated function that can be called when an error occurs in PHP.

This function must be able to handle at least two parameters (error level and error message), but can accept up to five parameters (optional: file, line-number, and error context):

Syntax

error_function(error_level, error_message,
error_file, error_line, error_context)
Parameter Description
error_level

Mandatory. Defines error report levels for user-defined errors. It must be a numeric value.

See the following table: Error report levels.

error_message Mandatory. Defines error messages for user-defined errors.
error_file Optional. Specifies the filename where the error occurred.
error_line Optional. Specifies the line number where the error occurred.
error_context Optional. Specifies an array containing each variable in use and their values when an error occurs.

Error Report Level

These error report levels are different types of errors that the error handler is intended to handle:

Value Constant Description
2 E_WARNING Non-fatal run-time errors. Do not pause script execution.
8 E_NOTICE

Run-time notification.

The script detects that an error may have occurred, but it may also occur during normal script execution.

256 E_USER_ERROR Fatal user-generated errors. Similar to E_ERROR set by the programmer using the PHP function trigger_error().
512 E_USER_WARNING Non-fatal user-generated warnings. Similar to E_WARNING set by the programmer using the PHP function trigger_error().
1024 E_USER_NOTICE User-generated notifications. Similar to E_NOTICE set by the programmer using the PHP function trigger_error().
4096 E_RECOVERABLE_ERROR Catchable fatal errors. Similar to E_ERROR, but can be caught by user-defined handlers. (See set_error_handler())
8191 E_ALL

All errors and warnings, except for level E_STRICT.

(In PHP 6.0, E_STRICT is part of E_ALL)

Now, let's create a function to handle errors:

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

The code above is a simple error handling function. When it is triggered, it retrieves the error level and error message. Then it outputs the error level and message, and terminates the script.

Now that we have created an error handling function, we need to determine when to trigger the function.

Set Error Handler

PHP's default error handler is the built-in error handler. We plan to make the above function the default error handler during script execution.

You can modify the error handler to apply only to certain errors, so the script can handle different errors in different ways. However, in this example, we plan to use our custom error handler for all errors:

set_error_handler("customError");

Since we want our custom function to handle all errors, set_error_handler() only requires one parameter, and a second parameter can be added to specify the error level.

Example

To test this error handler, output a non-existent variable:

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

The output of the above code should be similar to this:

Error: [8] Undefined variable: test

Triggering Error

It is very useful to trigger an error at the location where user input data is entered in the script, when the user's input is invalid. In PHP, this task is completed by trigger_error().

Example

In this example, an error will occur if the "test" variable is greater than "1":

<?php
$test=2;
if ($test>1)
{
trigger_error("Value must be 1 or below");
}
?>

The output of the above code should be similar to this:

Notice: Value must be 1 or below
in C:\webfolder\test.php on line 6

You can trigger an error at any location in the script by specifying the error level with the second parameter.

Possible error types:

  • E_USER_ERROR - Fatal user-generated run-time error. The error cannot be recovered. The script execution is interrupted.
  • E_USER_WARNING - Non-fatal user-generated run-time warning. The script execution is not interrupted.
  • E_USER_NOTICE - Default. User-generated run-time notification. The script found a possible error, or it may occur when the script is running normally.

Example

In this example, if the "test" variable is greater than "1", an E_USER_WARNING error occurs. If an E_USER_WARNING occurs, we will use our custom error handler and terminate the script:

<?php
//error handler function
function customError($errno, $errstr)
 { 
 echo "<b>Error:</b> [$errno] $errstr<br />";
 echo "Ending Script";
 die();
 }
//set error handler
set_error_handler("customError",E_USER_WARNING);
//trigger error
$test=2;
if ($test>1)
 {
 trigger_error("Value must be 1 or below",E_USER_WARNING);
 }
?>

The output of the above code should be similar to this:

Error: [512] Value must be 1 or below
Ending Script

Now that we have learned how to create our own errors and how to trigger them, let's study error logging.

Error Logging

By default, according to the error_log configuration in php.ini, PHP sends error logs to the server's error logging system or file. By using the error_log() function, you can send error logs to a specified file or remote destination.

Sending an error message to yourself via email is a good way to get notified of specific errors.

Send error messages via E-Mail

In the following example, if a specific error occurs, we will send an email with the error message and end the script:

<?php
//error handler function
function customError($errno, $errstr)
 { 
 echo "<b>Error:</b> [$errno] $errstr<br />";
 echo "Webmaster has been notified";
 error_log("Error: [$errno] $errstr",1,
 "someone@example.com","From: webmaster@example.com");
}
//set error handler
set_error_handler("customError",E_USER_WARNING);
//trigger error
$test=2;
if ($test>1)
 {
 trigger_error("Value must be 1 or below",E_USER_WARNING);
 }
?>

The output of the above code should be similar to this:

Error: [512] Value must be 1 or below
Webmaster has been notified

The email received from the above code is similar to this:

Error: [512] Value must be 1 or below

This method is not suitable for all errors. Routine errors should be logged on the server by using the default PHP logging system.