Reading And Writing To Compressed gzip Files

23rd April 2009 - 3 minutes read time
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.
  1. // read from file
  2. $inputfile = 'text.gz';
  3.  
  4. $filecontents = '';
  5.  
  6. $ifh = gzopen($inputfile, 'r');
  7.  
  8. while ( $line = gzgets($ifh, 1024) ) {
  9. $filecontents .= $line;
  10. }
  11. echo $filecontents;
  12. gzclose($ifh);
To write to a compressed file use the following script.
  1. // writing to a complessed file
  2. $inputfile = 'text.gz';
  3.  
  4. $string = 'lalalala';
  5. $filecontents = '';
  6.  
  7. $ifh = gzopen($inputfile, 'r');
  8.  
  9. while ( $line = gzgets($ifh, 1024) ) {
  10. $filecontents .= $line;
  11. }
  12. gzclose($ifh);
  13.  
  14. $ifh = gzopen($inputfile, 'w');
  15. if ( !gzwrite($ifh, $filecontents.$string) ) {
  16. // write failed
  17. }
  18.  
  19. gzclose($ifh);
To compress a normal file use the following script.
  1. // compress
  2. $inputfile = 'text.txt';
  3. $outputfile = 'text.gz';
  4.  
  5. // open files
  6. $ifh = fopen($inputfile, 'rb');
  7. $ofh = fopen($outputfile, 'wb');
  8.  
  9. // encode string
  10. $encoded = gzencode(fread($ifh, filesize($inputfile)));
  11.  
  12. if ( !fwrite($ofh, $encoded) ) {
  13. // write failed
  14. }
  15.  
  16. // close files
  17. fclose($ifh);
  18. fclose($ofh);
To uncompress a gzip file use the following script.
  1. // uncompress
  2. $inputfile = 'text.gz';
  3. $outputfile = 'text.txt';
  4.  
  5. $ofh = fopen($outputfile, 'wb');
  6.  
  7. $string = '';
  8.  
  9. $ifh = gzopen($inputfile, 'r');
  10. while ( $line = gzgets($ifh, 1024) ) {
  11. $string .= $line;
  12. }
  13.  
  14. if ( !fwrite($ofh, $string) ) {
  15. // write failed
  16. }
  17.  
  18. echo $string;
  19.  
  20. gzclose($ifh);
  21. 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.
  1. $ifh = gzopen($inputfile, 'r');
  2. $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.