Today I eventually started optimizing the performance (thereby reducing server load a bit). It appeared some pages of my larger websites have grown to round about 300 kb causing some latency for lower bandwidth visitor. Having a quite good connection myself, I didn't care about that much in the past. But that's ab pity, because it is very simple to add compression to pure PHP-generated content.
All you have to do is adding the following line to the top of your code:
ob_start("ob_gzhandler");
Requirements:
Requires PHP's zlib extension. Use phpinfo() to check for it.
And this is how the code works:
ob_start() activates output buffering for your PHP script. All output printed with print() or echo() after enabling the output buffering is buffered and held until you fetch it using ob_get_contents() or a similar function. If there is no ob_xxx function until the end of the script, the output-buffer will be flushed implicitely (as if ob_end_flush() got called).
The clue about "ob_gzhandler" is, it's a PHP built-in standard output handler compressing the data stored in the output buffer. The compression takes place on flush of the buffer.
What's the performance gain of GZIP...
The performance gain of delivering GZIP compressed textual content is very impressive! I just noticed the pages are reduced to 10% of the original size, making them being loaded 10 times faster than before.
Please keep in mind compressing data causes some additional CPU load. I didn't do tests about that yet, since I'm quite sure the much faster loading of my websites is cruicial exspecially as still a lot of people surf via low bandwidth.
What about about using GZIP and other output buffering in parallel?
Output buffers may be nested, by putting a clear structure of ob_start() and ob_ends() one inside another, like (pseudo-code):
ob_start(); // outside buffer ob_start(); // inside buffer ob_end_flush(); // flush the inside buffer (outside buffer will catch the content) ob_end_flush(); // flush the outside buffer (output the content to the user)
The same is allowed for ob_start("ob_gzhandler") of course. As a conclusion you should just ignore if there are other ob_start() statements in your PHP scripts, because if you put the ob_start("ob_gzhandler") statement before all other code, your own output buffer handling is affected by it by no means.