PHP Error Handling

PHP Error Handling
udemy2 placeholder image

No code is perfect, so you'll need to know how to handle errors when they occur. Thankfully, PHP gives us many different ways in which we can deal with errors gracefully to ensure the proper continuation of our code.

Handling Errors

There are a multitude of reasons why a script would throw an error while being run. Examples of these include a lack of disk space, attempting to access an API that is down, using incorrect or malicious user input, accessing a file or data from a database that doesn't exist, insufficient permissions to perform an operation, and many more.

Let's look at a basic example that could throw an error and then handle it when it does. Let's say we attempt to access a file that doesn't exist:

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

Assuming that file does not exist, you will get an error. However, you can avoid this by checking if the file exists before trying to open it, and if not, use the PHP die() function. This function stops the execution of a script and display whatever text is passed in, usually a user-friendly string of text to alert the user to what occurred.

Here is our new piece of code:

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

Now if the file doesn't exist you will just see:

	
    Sorry, the file you are trying to access does not exist!
	

Creating a Custom Error Handler

Sometimes, simply terminating the script and displaying a message isn't nearly enough. Sometimes you simply need to just run additional logic and keep the script going. For that we can create custom error handlers.

Custom error handlers, because they are custom, give you much more flexibility over how to handle the error. For example, you can choose to display a message to the user, display nothing and just take an alternative path, log it to a file or database, retry the operation, ignore the error, or terminate the script anyways.

Here is the basic syntax for a custom error handler function:

	
    error_function($errno, $errstr,  $errfile, $errline, $errcontext);
	

Only the first two parameters are required. The last three are optional. Here is a breakdown of what each parameter means:

  • errno: This is the error level you want to handle. More about this below.
  • errstr: This is the error in a string.
  • errfile: This is the name of the file that the error occurred on.
  • errline: This is the line number that the error occurred on.
  • errcontext: This is an array of the variable and values that were in use when the error occurred.
bluehost placeholder image

Error Levels

The first parameter, the errno, is an integer that specifies the error level you want to handle. Here are all the constants that represent an integer value that you can use as your error level:

  • E_ERROR: Errors that cause the script to terminate.
  • E_WARNING: Warnings that don't terminate the script.
  • E_PARSE: Errors generated at compile-time.
  • E_NOTICE: Notices that might indicate a problem, but not necessarily.
  • E_CORE_ERROR: Errors that occur when PHP starts-up.
  • E_CORE_WARNING: Warnings that occur when PHP starts-up.
  • E_USER_ERROR: This is an error created by you, the coder.
  • E_USER_WARNING: This is a warning created by you, the coder.
  • E_USER_NOTICE: This is a notice created by you, the coder.
  • E_STRICT: These are notices sent by PHP as suggestions for you to improve you code.
  • E_RECOVERABLE_ERROR: This is an error that can be recovered from if the user catches and handles it.
  • E_ALL: This is all errors and warnings.

Using a Custom Error Handler

Now that we know how to create a custom error handler, and how error levels work, let's actually define and use one.

Let's create a basic custom error handler that only uses the two required parameters:

	
    <?php
        function custom_error_handler($errno, $errstr) {
            echo("<strong>Error $errno</strong>: $errstr");
        }
    ?>
	

This simple error handler simply displays to us the error level that occurred and then the error itself. Now all we need to do is tell PHP to use this function when an error occurs. This is done using the set_error_handler() function and passing in the name of the handler function you'd like to use:

	
    <?php
        function custom_error_handler($errno, $errstr) {
            echo("<strong>Error $errno</strong>: $errstr");
        }

        set_error_handler("custom_error_handler");
    ?>
	

Now that we have defined our custom error handler and set it, let's try it out:

	
    <?php
        function custom_error_handler($errno, $errstr) {
            echo("[Error $errno]: $errstr");
        }

        set_error_handler("custom_error_handler");

        echo($handle_this);
    ?>
	
	
    [Error 8]: Undefined variable: handle_this
	

How cool is that?

Error Triggering

To better control the flow of your program, PHP lets you trigger errors manually instead of letting it happen normally. This is useful for when you detect that the state of your application is invalid and needs to change course. Triggering an error is done using the trigger_error function:

	
    <?php
        function custom_error_handler($errno, $errstr) {
            echo("[Error $errno]: $errstr");
        }

        set_error_handler("custom_error_handler");

        trigger_error("This is a manually triggered error!");
    ?>
	
	
    [Error 1024]: This is a manually triggered error!
	

Keep in mind that you can also define precisely what error level you want to trigger and also define in your custom error handler what error level you want to handle. Here's an example of specifying the error level on both the trigger call and the handler:

	
    <?php
        function custom_error_handler($errno, $errstr) {
            echo("[Error $errno]: $errstr");
        }

        set_error_handler("custom_error_handler", E_USER_WARNING);

        trigger_error("This is a manually triggered error!", E_USER_WARNING);
    ?>
	
	
    [Error 512]: This is a manually triggered error!
	
siteground placeholder image

Error Logging

When errors occur, it's usually not enough to simply tell the user that it has occurred. For the purposes of maintenance and improving the quality of your code, you're going to want to know that the error occurred at all. A great way to do this is by logging your errors using PHP's built-in error_log() function.

Used by itself, it will log an error that occurred to a file on your web server. Here is the basic syntax for it:

	
    error_log($message, $message_type, $destination, $extra_headers);
	

Here are the message types that you can use:

  • 0: This is the default option and will write it the log file on disk.
  • 1: This is used to send an email to the destination address.
  • 2: This option is no longer available.
  • 3: This appends the message to the file provided as the destination.
  • 4: This sends the message straight to the Server API.

Let's log an error to the disk using the message type 3 and pass in a file path:

	
    <?php
        function custom_error_handler($errno, $errstr) {
            error_log("[Error $errno]: $errstr", 3, "errors.log");
        }

        set_error_handler("custom_error_handler", E_USER_WARNING);

        trigger_error("This is a manually triggered error!", E_USER_WARNING);
    ?>
	

Now if you check the file errors.log, you should see:

	
    [Error 512]: This is a manually triggered error!
	

Now let's send ourselves an email whenever this error occurs:

	
    <?php
        function custom_error_handler($errno, $errstr) {
            error_log("[Error $errno]: $errstr", 1, "[email protected]", "From: [email protected]");
        }

        set_error_handler("custom_error_handler", E_USER_WARNING);

        trigger_error("This is a manually triggered error!", E_USER_WARNING);
    ?>
	

And just like that if you had access to [email protected] you would see the error emailed. The fourth parameter here is the email's subject.