Fast, Effective PHP Compression

by Jeff Starr on Monday, March 26, 2007 18 Responses

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


18 Responses
[ Gravatar Icon ]

bodi0#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!

[ Gravatar Icon ]

August Klotz#2

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 ]

Andreas#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.

[ Gravatar Icon ]

Perishable#4

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 ]

Andreas#5

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

[ Gravatar Icon ]

murray#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.

[ Gravatar Icon ]

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

}

[ Gravatar Icon ]

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

[ Gravatar Icon ]

murray#9

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

[ Gravatar Icon ]

Perishable#10

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

[ Gravatar Icon ]

onealhide#11

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 ]

Romano#12

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

[ Gravatar Icon ]

Jeff Starr#13

@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 ]

KOjunkie#14

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 ]

Jeff Starr#15

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 ]

Shahriat Hossain#16

Nice post dude :)

Trackbacks / Pingbacks
  1. How to Optimize Your Site with GZIP Compression | BetterExplained
  2. How To Optimize Your Site With GZIP Compression « SEO exploration
Comments are closed for this post

If you have or need further information, contact me.



Attention: Do NOT follow this link!