Green Acorn

Blog

PHP’s register_shutdown_function

With any PHP application, fatal errors will occur. Instead of presenting the user a white screen of death, it’s possible to programmatically execute a function just before a PHP completely shutsdown using the PHP function register_shutdown_function.

In the below example, the function error_get_last will provide the line, file, error type and message as an associative array. The example demonstrates how to register a custom shutdown function that will notify both the user and the administrator of the problem.

Note: This will not work if the file containing the register shutdown function has a parse error.

<?php

register_shutdown_function('shutdown_notify');

/**
 * Send a notification on a shutdown caused by an error
 */
function shutdown_notify() {
    $error = error_get_last();
    
    if(!empty($error) && in_array($error['type'], array(E_ERROR, E_USER_ERROR))) {
        echo '<h1>Sorry, something went wrong! The team has been notified.</h1>';

        $to = 'team@greenacorn-webdesign.co.uk';
        $subject = "[{$_SERVER['SERVER_NAME']}] Fatal error in {$error['file']} on line {$error['line']}";
        $message = var_export($error, true) . PHP_EOL;
        $message.= var_export($_SERVER, true) . PHP_EOL;
        
        mail($to, $message, $message);
    }
}
Author:
Posted in: PHP, Web Development

Leave a Reply

Your email address will not be published. Required fields are marked *

     

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>