PHP 5 Error Handling

Before we learn how to handle errors in PHP, we should first know what are errors.

An Error is said to have occurred when a piece of code returns unexpected result or stops abruptly due to some incorrect code for example division by zero, or infinite loop etc.

In PHP, we can set PHP configurations to show error messages in the browser or hide them.

PHP provides multiple ways to handle errors,

  1. Handling error in code using conditional statements or die() function
  2. Using Custom Error Handlers
  3. PHP error reporting

Let's cover each on of them with examples.


Using die() function

The die() function in PHP is used to display any message and exit out of current script at the same time. Hence once an error condition is detected, die() function can be used to exit the code execution.

An error can occur when we try to divide a number with zero, or try to open a file which doesn't exist, let's take an example and see how we can use die() function or conditional statement to handle error conditions.

<?php
    
    $fileName = "noerror.txt";
    // opening the file
    fopen($fileName, "r")
    or die("Unable to open file $fileName");
    
?>

In the code snippet above, we will get the message Unable to open file noerror.txt on the screen, if there is no file with name noerror.txt at the given location.

The die() function is an alias of exit() function which is also used to exit from code execution.

Now let's see how we can use conditional statements to handle error conditions. This type of error handling is useful when we know situations which may lead to errors beforehand.

For example, the below code will lead to error:

<?php
    
    function division($numerator, $denominator) {
        // perform division operation
        echo $numerator / $denominator;
    }
    
    // calling the function
    division(7, 0);
    
?>

Warning: Division by zero...

In such situation, where we know certain condition can lead to error, we can use conditional statement to handle the corner case which will lead to error. Let's fix the above code:

<?php
    
    function division($numerator, $denominator) {
        // use if statement to check for zero
        if($denominator != 0) {
            echo $numerator / $denominator;
        }
        else {
            echo "Division by zero(0) no allowed!";
        }
    }

    // calling the function
    division(7, 0);
    
?>

Division by zero(0) no allowed!

As you can see in the code above the error condition is handled. Now our code will not display any error on scree, rather it will display a message and exit gracefully.


Using Custom Error Handler

In PHP, we can use our custom method to display any message or execute any code when error occurs. All we have to do is set our method as the default error handler for PHP using the function set_error_handler()

Let's take an example:

<?php
    
    // custom function to handle error
    function studytonight_error_handler($error_no, $error_msg) {
        echo "Oops! Something unexpected happen...";
        echo "Possible reason: " . $error_msg;
        echo "We are working on it.";
    }
    
    // set the above function s default error handler
    set_error_handler("studytonight_error_handler");
    
    $result = 7 / 0;
    
?>

Oops! Something unexpected happen... Possible reason: Division by zero We are working on it.

We can define our own function like we did above with arguments $error_no and $error_msg and can handle them as we want. We can show custom message, log error in database, send email to the developer reporting the error etc.


PHP Error Reporting

PHP provides default error reporting mechanism which can be utilised to display messaged on screen when an error occurs.

Error handling is done to gracefully handle errors in the code and provide a better user experience to the end user.

We can use PHP function error_reporting() to set which errors to show and which errors to hide.

Following is the syntax for this function:

<?php
    // error reporting function
    error_reporting($reporting_level);
    
?>

The value for the variable $reporting_level defines which error to show and which errors to hide, if we do not provide any value for it, the error reporting will be set to default.

Following are the values that we can provide for setting various error levels:

Reporting LevelDescription
E_WARNINGOnly displays warning messages and doesn't stop the execution of the script.
E_NOTICEDisplays notice that occur during normal code execution.
E_USER_ERRORDisplay user generated errors i.e the custom error handlers.
E_USER_WARNINGDisplay user generated warning messages.
E_USER_NOTICEDisplay user generated notices.
E_RECOVERABLE_ERRORDisplays non-fatal errors.
E_ALLDisplay all errors and warnings.

This brings us to the conclusion of error handling in PHP. In the next tutorial we will learn about Exception Handling.