How can I unzip a .gz file with PHP?

gzopen is way too much work. This is more intuitive:

$zipped = file_get_contents("foo.gz");
$unzipped = gzdecode($zipped);

works on http pages when the server is spitting out gzipped data also.


PHP itself has a number of functions for dealing with gzip files.

If you want to create a new, uncompressed file, it would be something like this.

Note: This doesn't check if the target file exists first, doesn't delete the input file, or do any error checking. You really should fix those before using this in production code.

// This input should be from somewhere else, hard-coded in this example
$file_name = 'file.txt.gz';

// Raising this value may increase performance
$buffer_size = 4096; // read 4kb at a time
$out_file_name = str_replace('.gz', '', $file_name);

// Open our files (in binary mode)
$file = gzopen($file_name, 'rb');
$out_file = fopen($out_file_name, 'wb');

// Keep repeating until the end of the input file
while(!gzeof($file)) {
    // Read buffer-size bytes
    // Both fwrite and gzread and binary-safe
    fwrite($out_file, gzread($file, $buffer_size));
}

// Files are done, close files
fclose($out_file);
gzclose($file);

Note: This deals with gzip only. It doesn't deal with tar.