Code Snippet

Home » Code Snippets » PHP » Unzip Files

Unzip Files

<?php
$zip = zip_open("zip.zip");
if (is_resource($zip)) {
  while ($zip_entry = zip_read($zip)) {
    $fp = fopen("zip/".zip_entry_name($zip_entry), "w");
    if (zip_entry_open($zip, $zip_entry, "r")) {
      $buf = zip_entry_read($zip_entry, zip_entry_filesize($zip_entry));
      fwrite($fp,"$buf");
      zip_entry_close($zip_entry);
      fclose($fp);
    }
  }
  zip_close($zip);
}
?>

Reference URL

Subscribe to The Thread

  1. Thanks for the snippet! Awesome site. Very helpful.

  2. Wow, learn something new every day, never knew you could unzip files using PHP :) thanks for the snippet

  3. Prabhjot Singh

    Does this script work with simple PHP installed or any particular library or something needed with PHP ?

  4. linh

    i got problem with this message

    Fatal error: Call to undefined function zip_open() in /srv/www/vhosts/mysite.com/httpdocs/unzip.php on line 2

  5. Take it easy as:

    and it will unzip file on the server on same file path.

  6. If there are directories in the zip file, it will fail. An extra condition is necessary for properly extracting directories.

    $zh = zip_open('file.zip');
    while ($zip_entry = zip_read($zh)) {
    	$name = zip_entry_name($zip_entry);
    	if (substr($name, -1) == '/') {
    		mkdir($destination . $name);
    	} else {
    		$fh = fopen('zip/' . $name, 'w');
    		if (zip_entry_open($zh, $zip_entry, 'r')) {
    			$buf = zip_entry_read($zip_entry, zip_entry_filesize($zip_entry));
    			fwrite($fh, $buf);
    			zip_entry_close($zip_entry);
    		}
    		fclose($fh);
    	}
    }
    zip_close($zh);

Speak, my friend

At this moment, you have an awesome opportunity* to be the person your mother always wanted you to be: kind, helpful, and smart. Do that, and we'll give you a big ol' gold star for the day (literally).

Posting tips:
  • You can use basic HTML
  • When posting code, please turn all
    < characters into &lt;
  • If the code is multi-line, use
    <pre><code></code></pre>
Thank you,
~ The Management ~