Spring Sale! Save 30% on all books w/ code: PLANET24
Web Dev + WordPress + Security

Fast, Effective PHP Compression

PHP compression is an excellent method of conserving bandwidth and reducing client download times. We have already discussed an excellent method for CSS compression, and in this article we share a super-easy technique for compressing all PHP content without editing a single file.

Overview

Using two PHP files and two corresponding lines of .htaccess, it is possible to compress your PHP files via gzip-encoding. Browsers and other user-agents capable of interpreting gz-encoded data will employ the compressed content, while other user-agents will utilize the content uncompressed.

Step 0

Before we begin, it is important to determine if your server employs output buffering. If so, it may not be necessary to compress content via this method. Also, this PHP compression technique requires PHP version 4.0.5 or better.

Step 1

First, create two PHP files, gzip_start.php and gzip_stop. Open gzip_start.php and add this code:

<?php ob_start("ob_gzhandler"); ?>

Then, open gzip_stop.php and add this:

<?php ob_flush(); ?>

Save and upload both files to a convenient location on your server. The first file instructs the server to begin output buffering via gz-encoding. The second file instructs the server to transmit the buffered content to the user-agent, assuming it sends a header indicating its ability to process gzipped data.

Step 2

Finally, we need a way to include first file at the beginning of each PHP document and the second file at the end of each PHP document. Rather than manually adding include() or require() functions to every PHP document, we will summon the mysterious powers of .htaccess to do it all automatically. Simply add the following lines to your .htaccess file:

# dual file includes for PHP compression
php_value  auto_prepend_file  /specify/full/path/to/gzip_start.php
php_value  auto_append_file   /specify/full/path/to/gzip_stop.php

Edit the path in each line, save and upload the .htaccess file to your server. These two lines will ensure proper inclusion of both files to every PHP document subject to their influence (i.e., the containing directory and all subdirectories). The auto_prepend_file function literally prepends data, while the auto_append_file function, well, you get the idea..

Alternate Method

For an even easier PHP-compression method, simply place the following code before the (X)HTML content in any PHP script:

<?php if (substr_count($_SERVER['HTTP_ACCEPT_ENCODING'], 'gzip')) ob_start("ob_gzhandler"); else ob_start(); ?>

In this case, the ob_flush() command is unnecessary as PHP inherently flushes the buffer. The script delivers gzipped content to capable browsers and uncompressed content to incapable browsers. It’s a win-win!

Resources

About the Author
Jeff Starr = Creative thinker. Passionate about free and open Web.
USP Pro: Unlimited front-end forms for user-submitted posts and more.

16 responses to “Fast, Effective PHP Compression”

  1. Thanks, guys, this is all i need – really fast and easy to configure powerfull (9x times) compression! This method work for me great, no plugins/modules/etc to add! Keep going that way, greets!

  2. August Klotz 2007/05/30 12:19 am

    Just a note:
    In the first PHP-compression method you employ the function ob_start("ob_gzhandler"); without first testing for the presence of the required Apache extension, zlib. Replacing that first line with a simple check is an easy way to prevent unnecessary errors during implementation. Something such as the following would definitely do the trick:

    <?php if(extension_loaded('zlib')){ob_start('ob_gzhandler');} ?>

    ..and likewise, replace the closing function <?php ob_flush(); ?> with this:

    <?php if(extension_loaded('zlib')){ob_end_flush();}?>

  3. I tried this on an installation of Gallery 2, and while initially promising, the site grinded to a halt very soon. The bottleneck seems to be loading of images, which now takes several seconds each. Disabling this function restored previous speeds.

  4. Perishable 2007/10/14 9:34 am

    Andreas,
    Sorry to hear about your difficulties with Gallery 2. Rest assured that the method of PHP compression outlined in this article is standard stuff and employed quite commonly, working very effectively on many sites around the Web. Most likely, the problem you were experiencing involved a conflict associated with Gallery 2’s inability to properly coordinate g-zipping with its image-processing routines. That is to say that g-zipping works great most (like, 99%) of the time, but may experience inconsistencies when implemented with various third-party applications. In any case, thanks for the input, and good luck with Gallery 2 ;)
    Regards,
    Jeff

  5. Thanks, Jeff. I will try asking in the G2 forums for any tips on making compression work on G2.

  6. just to say that this script was working nice – however my xhtml and css validation links no longer worked, checking their output showed they did not like the compression but passed the condition ok $_SERVER[‘HTTP_ACCEPT_ENCODING’] – I plan to write a routine to avoid compression for certain URL’s.. should do the trick.

  7. here’s my working code…

    if ( isset( $_SERVER['HTTP_ACCEPT_ENCODING'] ) && substr_count($_SERVER['HTTP_ACCEPT_ENCODING'], 'gzip') ) {
       ob_start("ob_gzhandler");

    } else {
       ob_start();

    }

  8. Very nice! I take it that this script has resolved the issue with XHTML and CSS validation links? Seems absolutely logical that this bit of PHP negotiation would do the trick (don’t know why I didn’t think of it myself). If so, excellent work, and thank you for sharing it with us! :)

  9. better late than never – yes.. this little code addition avoids all the validation issues I was having – thanks again.

  10. Perishable 2008/06/22 8:11 am

    Excellent, murray — thanks for the follow-up! ;)

  11. onealhide 2008/07/30 9:34 pm

    thanks i can get much informations form you
    yes i get informations for upload mor 2 Mb you just put to on .htaccess

    php_value upload_max_filesize 1024M
    php_value post_max_size 1024M
    php_value max_execution_time 200
    php_value max_input_time 200

  12. Many thanks, Jeff for your info..
    A question: i have a vps, can this string overload my server?

Comments are closed for this post. Something to add? Let me know.
Welcome
Perishable Press is operated by Jeff Starr, a professional web developer and book author with two decades of experience. Here you will find posts about web development, WordPress, security, and more »
Banhammer: Protect your WordPress site against threats.
Thoughts
I live right next door to the absolute loudest car in town. And the owner loves to drive it.
8G Firewall now out of beta testing, ready for use on production sites.
It's all about that ad revenue baby.
Note to self: encrypting 500 GB of data on my iMac takes around 8 hours.
Getting back into things after a bit of a break. Currently 7° F outside. Chillz.
2024 is going to make 2020 look like a vacation. Prepare accordingly.
First snow of the year :)
Newsletter
Get news, updates, deals & tips via email.
Email kept private. Easy unsubscribe anytime.