Anyone who has done any development with PHP will be familiar with the infamous White Screen of Death; a blank browser window indicating that something horrible has gone wrong. A common cause, for me at least, is making a method call on a null object – easy to do in an object oriented architecture.

The exact reason as to why your script has gone splat will be reported in the log file, but from a UX standpoint, giving a blank screen to your customers is far from ideal. It is particularly problematic in complicated platforms like Elgg and Known, which use output buffering and have a plugin architecture.

Here’s a quick bit of code which can catch many (all?) of these fatal errors, and at least echo something. A variation of this is already in Known. Place the code somewhere towards the start of your script…

register_shutdown_function(function () {
        $error = error_get_last();
        if ($error["type"] == E_ERROR) {
            
            // If you use output buffering, chuck away any existing buffer
            ob_clean();

            // Set an appropriate HTTP error code
            http_response_code(500);

            // Construct your error message
            $error_message = "Fatal Error: {$error['file']}:{$error['line']} - \"{$error['message']}\", on page {$_SERVER['SERVER_NAME']}{$_SERVER['REQUEST_URI']}";

            // Display a friendly message to your customers, giving them an option to email you about it!
            echo "

Sorry, FizzBuzz experienced a problem!

"; echo "FizzBuzz experienced a problem with this page and couldn't continue. The technical details are as follows:

"; echo "$error_message"; echo "

If you like, you can email us for more information

."; // You'll also want to write the error to your log error_log($error_message); exit; } });

Hope this is useful to you!

5 thoughts on “Stopping (most) WSoD in PHP

  1. Yeah, some things still aren’t caught – so for example, if you redeclare a function. But, it does catch things like calling unrecognised methods or functions – which can be handy if you’re running plugins that require modules etc.

Leave a Reply