PHP and Zip Files
Mar 13, 2008 · 2 minute readCategory: phpzip
This is post is now quite old and the the information it contains may be out of date or innacurate.
If you find any errors or have any suggestions to update the information please let us know or create a pull request on GitHub
PHP has a built in class for dealing with zip files which allows you to create them, unpack them, add and delete things from them and generally use them within your scripts.
Recently on a spidering / product feed integration job that I have been working on I needed to grab a load of image zip files and unpack them all into a folder called ‘images/’ (surprisingly enough)
Here is how I did it:
function unpack_zips($directory, $destination = 'images/'){
$files = dir_list($directory);
//print_r($files);
$zips = array();
foreach($files as $k=>$file){
if(stristr($file, '.zip')){
$zips[] = $directory . $file;
}
}
print_r($zips);
$zip = new ZipArchive;
foreach($zips as $z){
if ($zip->open($z) === TRUE) {
$zip->extractTo($directory . $destination);
$zip->close();
//echo "<h3>$z OK</h3>";
} else {
echo"<h3 style=\"color: red;\">$z Failed</h3>";
bottom();
}
}
}
function dir_list($directory){
echo $directory;
if ($handle = opendir($directory)) {
while (false !== ($file = readdir($handle))) {
if($file != '.' && $file != '..'){
$return[] = $file;
}
}
closedir($handle);
return $return;
}else{
return false;
}
}
There are two functions. The first function is the one that deals with the Zip files. The second function is called by the first function and simply lists all files within a specified directory.
These two functions combined allowed me to find all zip files in a particular folder and then unpack them all into a destination folder.
Related Resources
http://www.phpclasses.org/browse/package/945.html
http://www.phpit.net/article/creating-zip-tar-archives-dynamically-php/