Jump Menu : Content | Explore | Comments | Search | Home | Sitemap | Contact | Login | Access.

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.

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.

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.

Now, create two PHP files, "gzip_start.php" and "gzip_stop". Open gzip_start.php and add this:

<?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.

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!

References

Related articles

About this article

This is article #341, posted by Jeff Starr on Monday, March 26, 2007 @ 01:11pm. Categorized as Function, and tagged with apache, browser, compression, htaccess, mod_rewrite, optimize, php. Updated on November 05, 2007. Visited 26014 times. 14 Responses »

BookmarkTrackbackCommentSubscribeExplore

« Flash-Detection Triple-Threat • Up • Wild Bill Recommends: Bizarre Flash Diversions »


14 Responses

1 • May 12, 2007 at 2:00 am — bodi0 says:

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 • May 30, 2007 at 12:19 am — August Klotz says:

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 • October 11, 2007 at 9:06 am — Andreas says:

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 • October 14, 2007 at 9:34 am — Perishable says:

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 • October 14, 2007 at 9:48 am — Andreas says:

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

6 • April 9, 2008 at 4:55 am — murray says:

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 • April 9, 2008 at 5:21 am — murray says:

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 • April 9, 2008 at 10:00 am — Perishable says:

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 • May 16, 2008 at 1:11 pm — murray says:

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

10 • June 22, 2008 at 8:11 am — Perishable says:

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

11 • July 30, 2008 at 9:34 pm — onealhide says:

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 • July 30, 2008 at 11:20 pm — Romano says:

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

13 • August 3, 2008 at 7:58 am — Jeff Starr says:

@onealhide: Thanks for the code! :)

@Romano: of course, it all depends on your configuration, number of files, etc., however I have not yet heard of such a thing. For an average site, I am sure you’ll be fine ;)

Drop a comment


Trackbacks / Pingbacks

  1. How to Optimize Your Site with GZIP Compression | BetterExplained

Set CSS to lite theme
Set CSS to dark theme