Cool formatting for PHP fatal error on browser

Sergi Rodríguez  
20-04-2020 23:37  
3 minutos de lectura  

If you are PHP developer you usually get a "PHP fatal error" on your browser. And by default the text message is visually horrible rendered on browser. Let me share with you a few lines of code to make more readable those kind of errors.

First: enable error displaying

Well, this is an obvious detail: you must first enable error displaying. Take in account that by default usually the error are not displayed on browser, but only noted on the log files of your server. So you usually include something like this on top of your first PHP file being called:


to get all kind of errors to be showed on browser.

How does it look

The bad news are that the error message returned by PHP is not an HTML formatted text (?), what certainly is very paradoxical... taking in account that PHP acronym means PHP Hypertext Preprocessor... so in other words it has been made to output HTML in a first term! hehe...

How we can "pretiffy" it?

It is the new great look & feel i got:

This is the PHP code to get it:

function shutdown() {
    $e = error_get_last();
    if ($e['type'] === E_ERROR) {

        // = format
            $msg = isset($e['message']) ? $e['message'] : '';
            $msg = str_replace(array('Uncaught Exception:','Stack trace:')
                          ,array('<b>Uncaught Exception:</b><br />',
                                    '<b>Stack trace:</b>'),$msg);
            $msg = preg_replace('/[a-z0-9_\-]*\.php/i','$1<u>$0</u>',$msg);
            $msg = preg_replace('/[0-9]/i','$1<em>$0</em>',$msg);
            $msg = preg_replace('/[\(\)#\[\]\':]/i','$1<ss>$0</ss>',$msg);

        // = render
        echo "<style>u{color:#ed6;text-decoration:none;}"
            ."div{margin:3rem auto;line-height:1.4em;padding:2rem;"
            ."\n<body style='background-color:#101;color:#bab;'>"
            ."\n    <h2>Fatal PHP error</h2>"
            ."\n    <div>".nl2br($msg)."</div>"


The magic is done by the last code line, which set that PHP must run function 'shutdown' before finish the thread.

Note: you must not set the ini_set() commands i mentioned at top of this guide.

Etiquetas : php | development

Comentarios 0   Visitas 1053  


Añada su comentario:

(pregunta anti-robots)



¡¡ Le respondemos antes de 24h !!
Puede dejarnos su teléfono.

Puede rellenar el formulario (pulsar botón derecha) o bien aquí tiene nuestros datos de contacto.

(pregunta anti-robots)


Revisar consentimientos a cookies