Friday 2 February 2007

Compress Webpage Even the Server doesn't support GZIP

Use gzip compression, you can save a lot of band width and your visitors also get better loading speed. But some odd servers do not enable this function. Now here is method to do it manually with php code.

First, save the highlighted code in the end of the page
Then, make your page like this

<?php?
include('gzipOut.php'); //first include our functions
?>
..................
..................//Put your content here
..................
<?php?
doGzipout(); //finally call gzip function
?>

Simple, right?
It's tricky, yet at most circumstances, we don't need it.





<?php
ob_start
();//Open flush
ob_implicit_flush(0);//
//*****************************************************************//
//Name:canGzip()
//Function:Check whether the client support gzip
//Parameter:
//Return Value: "gzip", "x-gzip", False
//*****************************************************************//
function canGzip()
{
//if (headers_sent() connection_status)

//return false;

if (strpos('King'.$_SERVER["HTTP_ACCEPT_ENCODING"], 'gzip') !== false)

return
"gzip";

if (
strpos('King'.$_SERVER["HTTP_ACCEPT_ENCODING"], 'x-gzip') !== false)

return
"x-gzip";

return
false;
}

//*****************************************************************//
//Name:doGzipOut($level, $debug)
//Function:compress the data in the flush and output
//Parameter:$level-compression level, 0 = no, 9 = max
// $debug-whether to output debug information, 1 = output, 0 = no
//Return Value:
//*****************************************************************//
function doGzipOut($level = 1, $debug = 0)
{

$ENCODING = canGzip();
if (
$ENCODING)
{
echo
"n<!-- Use compress $ENCODING -->n";

$contents = ob_get_contents();
ob_end_clean();

if (
$debug)
{
$s = "<p>Not compress length: ".strlen($contents);

$s .= "<br/>Compressed length: ".strlen(gzcompress($contents,$level));

$contents .= $s;
}

header("Content-Encoding: $ENCODING");
echo
"x1fx8bx08x00x00x00x00x00"; //???

$size = strlen($contents);
$crc = crc32($contents);
$contents = gzcompress($contents, $level);

$contents = substr($contents, 0, strlen($contents) - 4); //???

echo $contents;
echo
pack('V',$crc);
echo
pack('V',$size);

exit;
}
else
{
ob_end_flush();
exit();
}
}

?>

No comments:

Post a Comment