How to determine wether ob_start(); has been called already

C.O. picture C.O. · May 15, 2011 · Viewed 8.8k times · Source

I use output buffering for gzip compression and access to what was put out before in a PHP script:

if(!ob_start("ob_gzhandler")) ob_start();

Now if that script gets included in another script where ob_start() already is in use I get a warning:

Warning: ob_start() [ref.outcontrol]: output handler 'ob_gzhandler' cannot be used twice in filename on line n

So I'd like to test wether ob_start() has already been called. I think ob_get_status() should be what I need but what is the best way to use it in testing for this?

Answer

Gumbo picture Gumbo · May 15, 2011

ob_get_level returns the number of active output control handlers and ob_list_handlers returns a lift of those handlers. So you could do this:

if (!in_array('ob_gzhandler', ob_list_handlers())) {
    ob_start('ob_gzhandler');
} else {
    ob_start();
}

Although in general you can call ob_start any number of times you want, using ob_gzhandler as handler cannot as you would compress already compressed data.