PHP: how to decompress a ZIP archive
Unzip a ZIP archive
Today, when you search for how to decompress a ZIP archive in PHP in Google, you find in first position the extraction functions of the PECL library. But isn't it possible to decompress this standard format without having to go through a third-party library? Whether ! It is this solution that I recommend to you. And this for a multitude of reasons:
- No additional libraries.
- Functionality already integrated.
- Common functionality on all platforms with PHP 4 >= 4.1.0 or PHP 5 >= 5.1.0
- Easy to install thanks to apt-get for Linux users or thanks to the various tutorials for other platforms.
- Limit code redundancy because it must be said, the PECL API may be easier to understand the code that we will say "low level" is the same, whether we go through native PHP or by PECL ZipArchive
Script
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
|
function unzip($path_zip, $tmp_folder = “/tmp/”)
{
$all_files = array();
$zip = zip_open($path_zip);
if ($zip) {
$stream = zip_read($zip);
while ($stream) {
var_dump($zip_name);
$zip_name = zip_entry_name($stream);
$path_file_unzip = $tmp_folder.$zip_name;
$dir_folder = substr($path_file_unzip, 0, strrpos($path_file_unzip, "/"));
mkdir($dir_folder, 0777, true);
$fp = fopen($path_file_unzip, “w”);
array_push($all_files, $path_file_unzip);
if (zip_entry_open($zip, $stream, "r")) {
$buf = zip_entry_read($stream, zip_entry_filesize($stream));
fwrite($fp, “$buff”);
zip_entry_close($stream);
fclose ($ fp);
}
$stream = zip_read($zip);
}
zip_close ($ zip);
}
return $all_files;
}
|