Mr. B.
Mr. B.

Reputation: 8697

PHP performance: gzcompress() vs ob_start('ob_gzhandler')

I'm wondering, how to compress my output best.

Usually I just add ob_start('ob_gzhandler') at the top of my index.php, to compress the whole output.

I'm using a simple caching-Class to store the generated HTML in a file (index.cache.htm) instead of rebuilding it on every refresh. The content of index.cache.htm is minified due to a better performance.

Couldn't I compress the cached content instead of using ob_start('ob_gzhandler')?

Example 1 (caching the buffered output):

ob_start();                               // start buffer
$b = ob_get_contents();                   // get buffer
ob_end_clean();                           // free buffer

$b = CustomHTMLMinifyFunction($b);        // minify the HTML
$b = gzcompress($b);                      // compress the HTML
file_put_contents('index.cache.htm', $b); // save file

Example 2 (caching explicit data):

$d = 'Some data, e.g. JSON';              // some data
$d = gzcompress($d);                      // compress data
file_put_contents('data.cache.txt', $d);  // save file

What's the difference or best practise? Thanks in advance!

Edit: Does it ever make sense to store the compressed data in a file? Or is it only useful while outputting the data?

Upvotes: 1

Views: 2863

Answers (1)

RandomSeed
RandomSeed

Reputation: 29759

ob_start:

The [callback] function will be called when the output buffer is flushed (sent) or cleaned (with ob_flush(), ob_clean() or similar function) or when the output buffer is flushed to the browser at the end of the request.

In other words, ob_get_contents() will return the output buffer uncompressed contents:

$log = 0;

function callback($input){
    global $log;
    $log += 1;
    return ob_gzhandler($input);
}

ob_start('callback');
$ob = ob_get_contents();

echo $log; // echoes 0, callback function was not called

You must compress the output of ob_get_contents() if you want to cache a compressed version of the output data.

But you must configure your web server so that it is aware the files are pre-compressed (instructions for Apache). You can't just send compressed files to your client without setting proper headers.

To answer your edit, it makes sense to pre-compress your cache, otherwise the content is compressed on the fly. Also keep in mind that some clients do not support compression: you should keep an uncompressed version of your files if you want to be able to serve them.

Upvotes: 3

Related Questions