How can I extract or uncompress gzip file using php?

PHPServer Side ProgrammingProgramming

The zipped files can be unzipped or decompressed using PHP’s gzread function. Below is the code example for the same −


$file_name = name_of/.dump.gz';
$buffer_size = 4096; // The number of bytes that needs to be read at a specific time, 4KB here
$out_file_name = str_replace('.gz', '', $file_name);
$file = gzopen($file_name, 'rb'); //Opening the file in binary mode
$out_file = fopen($out_file_name, 'wb');
// Keep repeating until the end of the input file
while (!gzeof($file)) {
   fwrite($out_file, gzread($file, $buffer_size)); //Read buffer-size bytes.
fclose($out_file); //Close the files once they are done with


This will produce the following output −

The uncompressed data which is extracted by unzipping the zipped file.

The path of the zipped file is stored in a variable named ‘file_name’. The number of bytes that needs to be read at a time is fixed and assigned to a variable named ‘buffer_size’. The output file would not have the extension of .gz, hence the output file name is stored in a variable named ‘out_file_name’.

The ‘out_file_name’ is opened in a write binary mode to append contents into it after reading from the extracted zip file. The ‘file_name’ is opened in read mode, and the contents are read using the ‘gzread’ function and these contents extracted are written into the ‘out_file’. A while loop runs to make sure that the contents are read until the end of the file.

Updated on 09-Apr-2020 11:15:49