首页/Home PHP Common Programming Optimize Your PHP Site With Output Compression

Optimize Your PHP Site With Output Compression

PrintE-mail
Tuesday, 05 February 2008 17:00  

The thought is that less data to send, less time to spend!
Generally, there are at least three methods you can consider.

The first one, PHP has a built-in output compression system that will allow it to make the web pages smaller. To try out output buffering, you need to adjust two directives in the php.ini file:

output_buffering = Off (change the Off to On)
output_handler = (switch to output_handler = ob_gzhandler )

The second method, just place this at the very top of all your PHP pages and it will send gzip-compressed output to the browsers. This method is dependant on the Apache server and in addition, the mod_gzip module must be installed and loaded.

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

The methods mentioned above is quick and easy, but the downfalls are that it only works on Apache with mod_gzip. Not only that, but according to the PHP manual, that is not the preferred method for gzipping.

(From the PHP manual at php.net)
note that using zlib.output_compression is preferred over ob_gzhandler().

Another method of gzipping is as follows:

<?php
// Require this function on your pages
function echoGzippedPage()
{
if (
headers_sent() ){
$acceptEncoding = false;
} else if (
strpos($_SERVER['HTTP_ACCEPT_ENCODING'], 'x-gzip') !== false ) {
$acceptEncoding = 'x-gzip';
} else if (
strpos($_SERVER['HTTP_ACCEPT_ENCODING'],'gzip') !== false ) {
$acceptEncoding = 'gzip';
} else {
$acceptEncoding = false;
}

if (
$acceptEncoding ) {
$content = ob_get_clean();
header('Content-Encoding: ' . $acceptEncoding);
echo
"\x1f\x8b\x08\x00\x00\x00\x00\x00";
$size = strlen($content);
$content = gzcompress($content, 9);
$content = substr($content, 0, $size);
echo
$content;
exit();
} else {
ob_end_flush();
exit();
}
}

// At the beginning of each page call the following two functions
ob_start();
ob_implicit_flush(0);

// Then do whatever you want on the page
echo file_get_contents('bigfile.txt');

// Call the function to output everything as gzipped content.
echoGzippedPage();
?>

You can test how those methods mentioned above can help you make your site faster. Any doubt, don't hesitate to contact me.