Search code examples
phpoutput-buffering

How to tell if the function is called from an output buffering callback?


In a function, how can I find out if it's been called from an output buffering callback (not necessarily directly)?

function foo() {
    if (magic here ????)
        $log->write("foo:Callback") 
    else
        $log->write("foo:Normal")
}

function calls_foo() {
    ...stuff
    foo();
}

calls_foo() // should log foo:Normal

ob_start('calls_foo')

    ...stuff

// should log foo:Callback at the end of the script

Solution

  • Check $debug = debug_backtrace(). If the debug array is 1 long then you get called from main which means this is an ob callback called at the end of the request. Then you can iterate the array and look at the 'function' key of each array for an ob flushing function.