Categories
PHP
Javascript
MySQL
C#
VB
VB.NET
ASP.NET
Regex
Packaging & compression
General Web Tech
Tech Speak


Google


This website looks best on firefox.
 
Resource Center : PHP : <PHP and compression/archiving, with examples>

PHP and compression/archiving, with examples

Posted by: Floresense Team
Pages: 1  2  3  4  


Using gZip:
This library's core comes from: http://www.gzip.org/zlib/

The gZip functions allow you to read and write .gz files. All those popular .tar.gz files in linux environments are first tar compressed(which is another compression format) and then gzip compressed.

You can find more information on how to tar files into an archive here.

People usually tar and then gzip because, gzip is not an archiving format, it can only compress a single file.

This library is not enabled by default in PHP (Non-windows). The windows version of PHP has built-in support for this library. No need for installing any extensions.

Compressing a file with gZip and creating .gz file

$outFilename = 'zlibtest.gz';
$fileContents = "Only a test, test, test, test, test, test, test, test!n";



// open file for writing with maximum compression
$zp = gzopen($outFilename, "w9"); //w9 states that file should be opened with compression level is 9

// write string to file
gzwrite($zp, $fileContents);

// close file
gzclose($zp);





File modes:
Methods for gz, bz2 (which we see in next page) are all as easy as using fopen, fread, fwrite and fclose.

Also, as in fopen() we mention a file open 'mode' attribute in gzopen.
In above example it is "w9", which is equivalent to "w" mode which means 'open file for writing'.

This mode attribute can take all values that an fopen method can take.
Further, we can use it to mention the compression level (w9 or wb9) or a strategy: f for filtered data as in "wb6f",
h for Huffman only compression as in "wb1h".


Decompress a .gz file
Two steps:
1. Read the contents from the .gz file (automatically decompresses content)
2. Write to a new file using fopen, fwrite and fclose methods in PHP

//Open file for reading
$zp2 = gzopen($filename, "r");

//read chars
while (!gzeof($zp2)) {
$str .= gzread($zp2,1);
}
//output
echo "$str<br/>";

Also, there's a quicker statement if we want to read a .gz compressed file and print out contents to the output.
readgzfile($filename);

Pages: 1  2  3  4  

Advertisement

2005 - 2008 © Floresense.com