Output buffering PHP Apache mod gzip mod deflate

Till recently most of my php scripts were working fine on the servers with instantaneous outputs as and when a echo statement came. One issue that popped a lot on localhost was that of chunky outputs; that is the outputs of big scripts came out in chunks rather than smoothly with every echo or print statement. After some research flush() was found to be the solution for this output buffering issue. So what happened was that php was buffering the output and giving it out in good-sized chunks.

PHP may not be the only place where the output gets buffered. Between PHP and the browser lies Apache is also can buffer the output. Enabling mod_deflate/mod_gzip can lead to output buffering. Many cPanels have an option called "Optimise Website" option where users can select the file types on which compression is to be applied.
Enabling that options enables mod_gzip or mod_deflate which then compresses all output being send to the browser. Now along with compression it may lead to some amount of buffering and then any calls to flush() or ob_flush() inside php shall appear to have no effect since apache will now buffer the output.

So a better option is to selectively compress mime types. To keep output from buffering its better not to compress text/html and text/plain and everything else.
Mime types to compress can be specified in the "Optimise Website" section of cPanel.
To compress only javascript, css , gifs and pngs and flash files

application/x-javascript text/css text/xml image/png image/gif text/javascript application/x-shockwave-flash

can be added to the mime types. Keeping text/html and text/plain away from compression will keep the output of php files smooth and prevent buffering or the chunky output scenario.

Another way to selectively compress files is by renaming them to .php and add ob_start("ob_gzhandler");  at the top. So to compress a style.css file it must be renamed to style.php and should be put at the top.
That php code compresses all output that follows in the script. For a better description : ob_gzhandler.
But this technique isnt good to be used with non-text files like images flash animations etc. So a selective mime specification in mod_gzip is good.







Last Updated On : 22nd November 2008

Subscribe to get updates delivered to your inbox

1 Comment + Add Comment

  • What? Don’t try and compress files like GIFs and PNGs for crying out loud – they’re already in a compressed format!

Leave a comment