15

I'm using CodeIgniter and I can't figure out how to unzip files!

Shamoon
  • 38,429
  • 77
  • 269
  • 518
  • 1
    A .gz file is different from a .zip file, even if normally a utility that is able to uncompress .zip files is also able to uncompress .gz files. – apaderno Jul 20 '10 at 18:41

5 Answers5

49

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.

Powerlord
  • 84,782
  • 17
  • 123
  • 168
  • 1
    I used this code and it work perfects . just asking how to make it works with folders inside gz file and how to show output folder of extracted files . – Salem Mar 13 '15 at 08:33
  • 2
    @RealMan gzip only supports single files. You need a .tar.gz for multiple files. I'm not sure if PHP has built-in support for tar or not. – Powerlord Mar 13 '15 at 20:14
9

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.

Danial
  • 1,319
  • 12
  • 14
5

If you have access to system():

system("gunzip file.sql.gz");
parts2
  • 776
  • 6
  • 11
3

Use the functions implemented by the Zlib Compression extension.

This snippet shows how to use some of the functions made available from the extension:

// open file for reading
$zp = gzopen($filename, "r");

// read 3 char
echo gzread($zp, 3);

// output until end of the file and close it.
gzpassthru($zp);
gzclose($zp);
apaderno
  • 26,733
  • 16
  • 74
  • 87
2

Download the Unzip library and include or autoload the unzip library

$this->load->library('unzip');
Karan Thakkar
  • 1,482
  • 2
  • 17
  • 24
Sarfraz
  • 367,681
  • 72
  • 526
  • 573