Reading And Writing To Compressed gzip Files

Reading and writing to compressed gzip files can be done in much the same way as reading and writing normal files. The main difference is the use of some special functions that compress and uncompress the data. Rather then use fopen() to open a file, you open a compressed file with gzopen(). This is the case for many of the file access functions, although you should be aware that they don't all work exactly the same as each other. Here are some examples of the compression functions in use. To read from a compressed file use the following script.
// read from file
$inputfile = 'text.gz';
 
$filecontents = '';
 
$ifh = gzopen($inputfile, 'r');
 
while ( $line = gzgets($ifh, 1024) ) {
    $filecontents .= $line;
}
echo $filecontents;
gzclose($ifh);
To write to a compressed file use the following script.
// writing to a complessed file
$inputfile = 'text.gz';
 
$string = 'lalalala';
$filecontents = '';
 
$ifh = gzopen($inputfile, 'r');
 
while ( $line = gzgets($ifh, 1024) ) {
    $filecontents .= $line;
}
gzclose($ifh);
 
$ifh = gzopen($inputfile, 'w');
if ( !gzwrite($ifh, $filecontents.$string) ) {
    // write failed
}
 
gzclose($ifh);
To compress a normal file use the following script.
// compress
$inputfile = 'text.txt';
$outputfile = 'text.gz';
 
// open files
$ifh = fopen($inputfile, 'rb');
$ofh =  fopen($outputfile, 'wb');
 
// encode string
$encoded = gzencode(fread($ifh, filesize($inputfile)));
 
if ( !fwrite($ofh, $encoded) ) {
    // write failed
}
 
// close files
fclose($ifh);
fclose($ofh);
To uncompress a gzip file use the following script.
// uncompress
$inputfile = 'text.gz';
$outputfile = 'text.txt';
 
$ofh =  fopen($outputfile, 'wb');
 
$string = '';
 
$ifh = gzopen($inputfile, 'r');
while ( $line = gzgets($ifh, 1024) ) {
    $string .= $line;
}
 
if ( !fwrite($ofh, $string) ) {
    // write failed
}
 
echo $string;
 
gzclose($ifh);
fclose($ofh);
Notice from these examples that you can open a compressed file using fopen(), but you need to use the 'b' flag to indicate to fopen that you want the file to be opened in a binary format. Basically, the two following calls are very much the same.
$ifh = gzopen($inputfile, 'r');
$ifh = fopen($inputfile, 'rb');
The gzopen() function can also take some other parameters as the mode. These include the compression level (eg. wb1 or wb9) or a strategy. The strategy can be either f for filtered (used as wb9f) or h for Huffman only compression (used as wb1h).

Add new comment

The content of this field is kept private and will not be shown publicly.
CAPTCHA
2 + 0 =
Solve this simple math problem and enter the result. E.g. for 1+3, enter 4.
This question is for testing whether or not you are a human visitor and to prevent automated spam submissions.