Simple PHP script for unzip function

Here’s a simple PHP function to unzip a ZIP file and retain directory structure – great for use when you can’t use exec(). The function will return false on error and true on success. Call it with the following code:

if (unzip('../mtm.zip'))
	echo 'Cool, it worked!';
else
	echo 'Uh oh, something went wrong.';
function unzip($zipfile) {
	$zip = zip_open($zipfile);
	if ($zip) {
		while ($item = zip_read($zip)) {
			$name = zip_entry_name($item);
			if (substr($name, -1) == '/') {
				if (!file_exists($name)) {
					$dir = mkdir($name);
					if (!$dir) {
						zip_close($zip);
						return false;
					}
				}
			} else {
				if (zip_entry_open($zip, $item, "r")) {
					$f = file_put_contents($name, zip_entry_read($item, zip_entry_filesize($item)));
					zip_entry_close($item);
					if ($f === false) {
						zip_close($zip);
						return false;
					}
				} else {
					zip_close($zip);
					return false;
				}
			}
		}
		zip_close($zip);
		return true;
	}
	return false;
}
[ad]

2 thoughts on “Simple PHP script for unzip function”

  1. $dir = mkdir($name);

    Why not

    $dir = mkdir($name,0755,true);

    It’s “dir”, chmod, “recursive”.

    With a folder like /Documentation/images (as in mybb…) your version doesn’t work.
    With the recursive param’ set to true, it works :)

    Have a nice day :)

  2. Well, it does work if the parent directories are already there and you’re running the script as a user who has access, but yes, this could make it easier for you if you are in a situation where the environment may not be clear.

Leave a Reply

Your email address will not be published. Required fields are marked *

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <s> <strike> <strong>