How to extract .gz file via PHP code

You can use following function to extract .gz files in server directory

function extract_gz($outFileName)
{   
    //This input should be from somewhere else, hard-coded in this example
  $file_name = $outFileName;

  // Raising this value may increase performance
  $buffer_size = 40960; // 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('extracted/'.$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);
}

If your file is too large, you can use add following code in the top of your PHP script:

ignore_user_abort(true); // Script will run in background even if you will close the browser
set_time_limit(0); // Set execution time unlimited
Back to blog

Leave a comment

Please note, comments need to be approved before they are published.