Saturday, December 16, 2006

Compressing files in PHP

by Justin Silverton

Zlib compression has been built into php since version 3 and it can be used to compress the output of your php applications (which can significantly decrease the amount of bandwidth of a page), but what you can also do is compress any file accessible from your webserver.

The code

The following are two functions: compress and uncompress, which can compress and uncompress a specified file.

function uncompress($srcName, $dstName) {
$string = implode(”", gzfile($srcName));
$fp = fopen($dstName, “w”);
fwrite($fp, $string, strlen($string));
fclose($fp);
}

function compress($srcName, $dstName)
{
$fp = fopen($srcName, “r”);
$data = fread ($fp, filesize($srcName));
fclose($fp);

$zp = gzopen($dstName, “w9″);
gzwrite($zp, $data);
gzclose($zp);
}

compress(”test.php”,”test.gz”);
uncompress(”test.gz”,”test2.php”);

Source code can be downloaded here

Description of related zlib functions

gzclose — Close an open gz-file pointer
gzcompress — Compress a string
gzencode — Create a gzip compressed string
gzeof — Test for end-of-file on a gz-file pointer
gzfile — Read entire gz-file into an array
gzgetc — Get character from gz-file pointer
gzgets — Get line from file pointer
gzgetss — Get line from gz-file pointer and strip HTML tags
gzinflate — Inflate a deflated string
gzopen — Open gz-file
gzpassthru — Output all remaining data on a gz-file pointer

No comments: