Fast, Effective PHP Compression

Post #341 categorized as Function, last updated on Apr 19, 2009
Tagged with apache, browser, compression, htaccess, mod_rewrite, optimize, php

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

Subscribe to Perishable Press


18 Responses

TopLeave a comment

[ Gravatar Icon ]

#1bodi0

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!

[ Gravatar Icon ]

#2August Klotz

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();}?>

[ Gravatar Icon ]

#3Andreas

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.

[ Gravatar Icon ]

#4Perishable

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

[ Gravatar Icon ]

#5Andreas

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

[ Gravatar Icon ]

#6murray

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.

[ Gravatar Icon ]

#7murray

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();

}

[ Gravatar Icon ]

#8Perishable

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! :)

[ Gravatar Icon ]

#9murray

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

[ Gravatar Icon ]

#10Perishable

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

[ Gravatar Icon ]

#11onealhide

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

[ Gravatar Icon ]

#12Romano

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

[ Gravatar Icon ]

#13Jeff Starr

@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 ;)

[ Gravatar Icon ]

#14KOjunkie

I feel a little foolish for asking, but what should the path structure look like for the .htaccess file, does it require http:// prefix?

# 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

Please advise,
thanks you,
Steve

[ Gravatar Icon ]

#15Jeff Starr

Hi KOjunkie, you want to use the absolute path to the file. No http:// prefix required. Each path will begin with a slash and look similar in structure to the example paths used in the tutorial.

An easy way to determine the absolute path of any file is to upload a PHP file into the same directory and place the following code within it:

<?php echo $_SERVER['DOCUMENT_ROOT']; ?>

..and then call the script by navigating to the PHP file in your browser.

Let me know if you need more assistance with this.
Cheers,
Jeff

[ Gravatar Icon ]

#16Shahriat Hossain

Nice post dude :)

[ Comments are closed for this post. ]

If you have or need further information, contact me.