Last active
November 3, 2022 22:17
-
-
Save liconti/2426617 to your computer and use it in GitHub Desktop.
PHP extract a subdirectory contained in a ZIP file to a destination path
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
function extract_zip_subdir($zipfile, $subpath, $destination, $temp_cache, $traverse_first_subdir=true){ | |
$zip = new ZipArchive; | |
echo "extracting $zipfile... "; | |
if(substr($temp_cache, -1) !== DIRECTORY_SEPARATOR) { | |
$temp_cache .= DIRECTORY_SEPARATOR; | |
} | |
$res = $zip->open($zipfile); | |
if ($res === TRUE) { | |
if ($traverse_first_subdir==true){ | |
$zip_dir = $temp_cache . $zip->getNameIndex(0); | |
} | |
else { | |
$temp_cache = $temp_cache . basename($zipfile, ".zip"); | |
$zip_dir = $temp_cache; | |
} | |
echo " to $temp_cache... \n"; | |
$zip->extractTo($temp_cache); | |
$zip->close(); | |
echo "ok\n"; | |
echo "moving subdir... "; | |
echo "\n $zip_dir / $subpath -- to -- > $destination\n"; | |
rename($zip_dir . DIRECTORY_SEPARATOR . $subpath, $destination); | |
echo "ok\n"; | |
echo "cleaning extraction dir... "; | |
rrmdir($zip_dir); | |
echo "ok\n"; | |
} else { | |
echo "failed\n"; | |
die(); | |
} | |
} | |
?> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
if(substr($temp_cache, -1) !== DIRECTORY_SEPARATOR)
can be rewritten asrtrim($x, DIRECTORY_SEPARATOR)