Search code examples
phperror-handlingwhoops

PHP Whoops error handle clear buffer


Issue

In procedural scripting the PHP Whoops Pretty Page handler content will be mixed with partial content from the applications buffer output. Whoops can appear scrambled or output inside a hidden html tag.

Question

How to clear the previous buffer before Whoops handler buffers?


Solution

  • The following solution worker for me:

    At the earliest point of your script and perhaps only in a DEBUG or DEVELOPER mode as I did you need to do:

    if(DEVELOPER_DEBUG === true)
        ob_start();
    

    Then where you declare Whoops I did:

    if(DEVELOPER_DEBUG === true)
    {
        $_whoops = new \Whoops\Run();
    
        $_whoops->pushHandler(function(){
            ob_clean();
        });
    
        $_handler = new \Whoops\Handler\PrettyPageHandler();
        $_whoops->pushHandler($_handler);
        $_whoops->register();
    }
    

    This worked flawlessly in my usage case in procedural scripting to clear any initial generated buffer before Whoops starts it's own output.

    Why it works

    ob_start() can be called multiple times, the buffer flush or clear function needs to be called the same number of times as start was called in sequence.

    By making your application start its own buffer it makes it a resource that can be cleared, Whoops always starts it's own buffer as well, so by registering a handler to clear the first buffer (your application) then on the event of an error, Whoops can clear that previous buffer.

    Buffer Control

    For example, each call of ob_start an incremental buffer is created.

    If you call ob_start 3 times you need to call ob_flush 3 times in order to output all buffered content.

    If you call it once you will only clear or flush the content generated before the next ob_start was declared.

    Could be adaptive for OOP.