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);

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

Reading & Writing

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

For a big file, this method tends to be a bit more memory efficient.

<?php
// open the resources, see above

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

// close the resources, see above
Posted in PHP