Home > Uncategorized > Simple PHP script for unzip function

Simple PHP script for unzip function

October 26th, 2009 Leave a comment Go to comments

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:

1
2
3
4
if (unzip('../mtm.zip'))
	echo 'Cool, it worked!';
else
	echo 'Uh oh, something went wrong.';
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
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;
}
Categories: Uncategorized Tags:
  1. No comments yet.
  1. No trackbacks yet.