Compress your output

HTML is a very wordy format, which means there is a lot of duplication in the form of HTML tags, but also in the main body of text. Furthermore, by default PHP will send text to Apache as soon as it is ready, which results in less efficient transfer of data.

The solution is to enable output buffering, and to use gzip compression for the buffers. Output buffering, if you were unaware, makes PHP store up its data into one big chunk, then send it to Apache all at once. Because all the data is kept together and sent all at once, PHP is able to compress it using gzip compression, which will generally reduce the content to around 33% of its original size (that is, 1MB will become 300KB).

Not all clients support receiving compressed content (every browser made in the last five years will), and to handle that PHP will only compress data if the client can support it - this means you can enable compression, and not have to worry about old clients because PHP will not send them compressed data.

To enable output buffering for all your scripts, open up your php.ini file and set output_buffering to 1 and output_handler to "ob_gzhandler" (without the quotes). You'll find those values already set in your php.ini already, so just change the existing values. You should check your phpinfo() output to make sure output buffering is enabled correctly.


Want to learn PHP 7?

Hacking with PHP has been fully updated for PHP 7, and is now available as a downloadable PDF. Get over 1200 pages of hands-on PHP learning today!

If this was helpful, please take a moment to tell others about Hacking with PHP by tweeting about it!

Next chapter: Don't use CGI >>

Previous chapter: Cache array data

Jump to:


Home: Table of Contents

Copyright ©2015 Paul Hudson. Follow me: @twostraws.