English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية

PHP Basic Tutorial

PHP Advanced Tutorial

PHP & MySQL

PHP Reference Manual

PHP Error Handling

In this tutorial, you will learn how to use PHP's error handling features to gracefully handle error situations.

Error Handling

Sometimes, your application may not run normally, leading to errors. There are many possible causes of errors, such as:

  • The web server may be out of disk space

  • The user may have entered an invalid value in the form field

  • The file or database record you are trying to access may not exist

  • The application may not have permission to write files on the disk

  • The services that the application needs to access may be temporarily unavailable

These types of errors are called runtime errors because they occur during script execution. They are different from syntax errors that need to be fixed before the script runs.

Professional applications must have the functionality to properly handle such runtime errors. This usually means informing users more clearly and accurately about what has gone wrong.

Understanding Error Levels

Generally, when a problem occurs that prevents the script from running normally, the PHP engine will trigger an error. Each error is represented by an integer value and an associated constant. The following table lists some common error levels:

Error LevelValueDescription
E_ERROR1

Fatal runtime errors that cannot be recovered. The execution of the script will stop immediately.

E_WARNING2

Runtime warnings. They are not fatal, and most errors belong to this category. The execution of the script will not stop.

E_NOTICE8

Runtime notifications. Indicates that the script has encountered a situation that may cause an error, although this situation may also occur during normal script execution.

E_USER_ERROR256

User-generated fatal error messages. This is similar to E_ERROR, but it is generated by the PHP script using the trigger_error() function instead of the PHP engine.

E_USER_WARNING512Non-fatal user-generated warning messages. This is similar to E_WARNING, but it is generated by the PHP script using the trigger_error() function instead of the PHP engine.
E_USER_NOTICE1024

User-generated notification messages. This is similar to E_NOTICE, but it is generated by the PHP script using the trigger_error() function instead of the PHP engine.

E_STRICT2048

Strictly speaking, it is not an error, but PHP will trigger when it encounters code that may cause problems or is not forward-compatible.

E_ALL8191

All errors and warnings, PHP 5.4.0 before E_STRICT except.

For more error levels, please refer toPHP error levelsfor reference.

Every time a PHP script encounters a problem, the PHP engine will trigger an error, but you can also trigger errors yourself to generate more user-friendly error messages. This way, you can make your application more complex. The following section describes some common methods used to handle PHP errors:

Basic error handling using the die() function

Consider the following example, which attempts to open a text file in read-only mode.

<?php
//Attempt to open a non-existent file
$file = fopen("sample.txt", "r");
?>

If the file does not exist, you may receive the following error:

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

By following some simple steps, we can prevent the user from receiving such error messages.

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

Now, if you run the above script, you will get the following error message:

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

As you can see, by implementing a simple check to see if the file exists before attempting to access it, we can generate more meaningful error messages to the user.

If the "sample.txt" file is not found, the die() function used above will only display a custom error message and terminate the current script.

Creating a custom error handler

You can create your own error handling function to handle runtime errors generated by the PHP engine. Custom error handlers provide greater flexibility and better control over errors, allowing them to check for errors and decide how to handle them, which may include displaying a message to the user, logging the error to a file or database, sending an email, attempting to fix the problem and continue, exiting script execution, or completely ignoring the error.
The custom error handling function must be able to handle at least two parameters (errno and errstr), but it can also choose to accept an additional three parameters (errfile, errline, and errcontext), as described below:

ParametersDescription
Required - The following parameters are required
errnoSpecify the error level as an integer. This corresponds to the appropriate error level constants (E_ERROR, E_WARNING, etc.)
errstrSpecify the error message as a string
Optional - The following parameters are optional
errfileSpecify the filename of the script file where the error occurred as a string
errlineSpecify the line number where the error occurred as a string
errcontextSpecify an array containing all variables and their values that exist when an error occurs. Useful for debugging

Here is a simple example of a custom error handling function. No matter how trivial, whenever an error occurs, this handler customError() is triggered. Then, it outputs the error details to the browser and stops the script execution.

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

You need to tell PHP to use your custom error handling function-Just call the built-in set_error_handler() function and pass the function name.

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

Error logging

Record error messages in a text file

You can also record the detailed error information into a log file as follows:

<?php
function calcDivision($dividend, $divisor) {
    if($divisor == 0) {
        trigger_error("calcDivision(): Division by 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("An issue occurred, please try again.");
}
set_error_handler("customError");
echo calcDivision(10, 0);
echo "This will never be printed.";
?>

Send error messages via email

You can also use the same error_log() function to send an email with detailed error information.

<?php
function calcDivision($dividend, $divisor) {
    if ($divisor == 0){
        trigger_error("calcDivision(): Division by 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, "[email protected]");
    die("An issue occurred, please try again. Error report has been submitted to the website administrator.");
}
set_error_handler("customError");
echo calcDivision(10, 0);
echo "This will never be printed out.";
?>

Trigger error

Although the PHP engine triggers errors when encountering script issues, you can also trigger errors yourself. This can help make your application stronger as it can mark potential issues before they become serious errors.

To trigger an error from within the script, call the trigger_error() function and pass the error message to be generated:

trigger_error("Something went wrong.");

Consider the following function that calculates the division of two numbers.

<?php
function calcDivision($dividend, $divisor) {
    return($dividend / $divisor);
}
 
//Call function
echo calcDivision(10, 0);
?>

If a zero value is passed as the $divisor parameter, the error generated by the PHP engine will be similar to the following content:

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

This message does not seem to contain much content. See the following example of generating an error using the trigger_error() function.

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

Now, the script generates the following error message:

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

As you can see, the error message generated by the second example more clearly illustrates the problem compared to the previous example.