Extracting GZIP Files with PHP

PHP comes with a nice zlib extension in its core. We're going to use it to extract a gzip compressed file.

The steps here are pretty simple:

  1. Open the gzip file with gzopen
  2. Open the destination file with fopen
  3. Transfer the data from the gzip file to the normal file
  4. Close the open resources

Most of these are really straight forward:

<?php
// open the gzip file
$gz = gzopen('/path/to/file.txt.gz', 'rb');
if (!$gz) {
    throw new \UnexpectedValueException(
        'Could not open gzip file'
    );
}

$dest = fopen('/path/to/file.txt', 'wb');
if (!$dest) {
    gzclose($gz);
    throw new \UnexpectedValueException(
        'Could not open destination file'
    );
}

// transfer ...

gzclose($gz);
fclose($dest);

The transfer step, however, can be done a few different ways.

Using stream_copy_to_stream

stream_copy_to_stream does about what you'd expect: take a source stream, copy it to the destination.

<?php
// open the resources, see above

stream_copy_to_stream($gz, $dest);

// close the resources, see above

stream_copy_to_stream can be a bit of a memory hog -- it will attempt to read the entire file into memory.

Reading & Writing

The alternative is to use gzread and fwrite to stream data from the gzip file to the extracted version.

It's possible to do this with stream_copy_to_stream via its last two arguments. This reads a bit better, however.

<?php
// open the resources, see above

while (!gzeof($gz)) {
    fwrite($dest, gzread($gz, 4096));
}

// close the resources, see above

#