PHP Error reporting via Emails

This tutorial provides a solution to receive email alerts when an uncontrolled error occurs.

Imagine that you have created a PHP application, hosted on an Apache Server and it is working smoothly. A few days later, a user complains about an error that is not known to you completely. Such unprocessed errors are very common in PHP applications. Therefore, to find these issues, we will program the PHP project to send email notifications when an error occurs.

For this to happen we need to detect and react when there is a fatal error that causes execution to stop unexpectedly. There is a PHP hook we can utilize for this purpose; register_shutdown_function.

What is register_shutdown_function?

register_shutdown_function is used to register a function for execution on shutdown.

register_shutdown_function ( callable $callback [, mixed $... ] ) : void

Registers a callback to be executed after script execution finishes or exit() is called.

Multiple calls to register_shutdown_function() can be made, and each will be called in the same order as they were registered. If you call exit() within one registered shutdown function, processing will stop completely and no other registered shutdown functions will be called.

When this function is called we can simply determine if and what error caused the execution to stop. This registration and check must be accessible by all the PHP files.

register_shutdown_function('mail_on_error');

function mail_on_error() {
  $error = error_get_last(); 
  if ($error['type'] == 1) {
    $emailAddress = 'example@example.com';
    $emailSubject = 'Error on my PHP Application';
    $emailMessage = '<h2>Error Reporting on :- </h2>[' . date("Y-m-d h:i:s", time()) . ']';
    $emailMessage .= "<h2>Error Number :- </h2>".print_r($error['type'], true).'';
    $emailMessage .= "<h2>Error String :- </h2>".print_r($error['message'], true).'';
    $emailMessage .= "<h2>Error File :- </h2>".print_r($error['file'], true).'';
    $emailMessage .= "<h2>Error Line :- </h2>".print_r($error['line'], true).'';
    $headers = "MIME-Version: 1.0" . "rn";
    $headers .= "Content-type:text/html;charset=UTF-8" . "rn";
    mail($emailAddress, $emailSubject, $emailMessage, $headers);
  }
}

This PHP snippet will prepare an informative email and sent it to ‘example@example.com’ when an important error occurs.