Fast, Effective PHP Compression

.htaccess made easy

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