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
More information on zlib related functions can be found here
8 Comments so far
Leave a reply






Hey and thanks for a great function! But when I use it my filenames get *.doc.gz and if I remove the .doc in the input file the gz-file is okay, but the zipped file has no extension.
Is there an easy way to solve this?
how are you calling these functions?
Have you tried:
compress(”test.doc”,”test.gz”);
I call it like you say, only that I use variables. I manage to get til gz-filename right, but if I open the compressed whatever I get a file of filetype file, ie the originally extension is gone. I also found out that srcName must be a abs path, since my files are not located in the same directory, but guess that makes no different.
function compress($srcName){
$fileinfo = pathinfo($srcName);
$ext = $fileinfo[’extension’];
$dstName = PATH. basename($srcName, “.$ext”) . “.gz”;
$fp = fopen($srcName, ‘r’);
$data = fread ($fp, filesize($srcName));
fclose($fp);
$zp = gzopen($dstName, “w9″);
gzwrite($zp, $data);
gzclose($zp);
}
my function, slightly different from yours, one parameter, removes the extension of the sourceName and puts on gz instead of using filename as param… I’ve tried both ways, same results.
Are your compressed files unalteret (regarding extension)?
Great piece of information. I have been looking for this gz compression tool to be called in PHP for quite some time and yours come in handy for my site, where I had to compress 1.2MB of sitemap file to conserve bandwidth.
Cheers!!
Hello
But… that don’t work with big files, someone knows how to uncompress a big file .gz?
Regards
hello there.
thanks for the info. but can i use compress and uncompress functions for directories?
i need to compress temp directory and send the .zip output to website for download (using php).
i tried to use zipfile class yesterday but the output is corrupted.
please help.
thanks!
[…] http://www.whenpenguinsattack.com/2006/12/14/compressing-files-in-php/ […]
I executed this code but how this can be used for compresiing a file in client side