I need to extract the contents of a directory within a zip archive in to an output directory.
The directory name inside the zip could be anything. However it will be the only directory in the base of the zip archive. There could be any number of files in the directory, in the zip archive, though.
The file structure inside the zip would be along theses lines:
- d0001
- My Folder
- view.php
- tasks.txt
- file1.txt
- picture1.png
- document.doc
The contents of the output directory needs to look like this:
- My Folder
- view.php
- tasks.txt
- file1.txt
- picture1.png
- document.doc
The code I currently have deletes the contents of the output directory and extracts the entire zip archive in to the directory:
function Unzip($source, $destination) {
$zip = new ZipArchive;
$res = $zip->open($source);
if($res === TRUE) {
$zip->extractTo($destination);
$zip->close();
return true;
} else {
return false;
}
}
function rrmdir($dir, $removebase = true) {
if(is_dir($dir)) {
$objects = scandir($dir);
foreach($objects as $object) {
if($object != "." && $object != "..") {
if(filetype($dir."/".$object) == "dir") rrmdir($dir."/".$object); else unlink($dir."/".$object);
}
}
reset($objects);
if($removebase == true)
rmdir($dir);
}
}
$filename = '/home/files.zip';
$dest = '/home/myfiles/';
if(is_dir($dest)) {
rrmdir($dest, false);
$unzip = Unzip($filename, $dest);
if($unzip === true) {
echo 'Success';
} else
echo 'Extraction of zip failed.';
} else
echo 'The output directory does not exist!';
All the function rrmdir()
does is remove the contents of the output directory.