How to Extract a GZ file with PHP

Posted on August 26, 2019 at 12:02 pm

A simple function to extract a .gz compressed file with PHP:

function php_extract_gz_file($gzfile, $savefileas, $removegz = false)
{
    if(!file_exists($gzfile)) return false;
 
    $gzopen_handle = gzopen($gzfile, 'rb');
 
    if(!$gzopen_handle) return false;
 
    $outfile_handle = fopen($savefileas, 'wb');
 
    if(!$outfile_handle) return false;
 
    while(!gzeof($gzopen_handle)) 
    {
        fwrite($outfile_handle, gzread($gzopen_handle, 4096));
    }
 
    fclose($outfile_handle);
 
    gzclose($gzopen_handle);
 
    if(!file_exists($savefileas)) return false;
 
    if($removegz) unlink($gzfile);
 
    return true;
}

Example usage:

if(php_extract_gz_file("compressed.gz", "uncompressed.txt", true))
{
    echo "GZ file uncompressed successfully!";
}
else
{
    echo "Failed to uncompress GZ file!";
}

Receive updates via email

Other Posts

Updated Posts