Skip to content

Instantly share code, notes, and snippets.

@liconti
Last active November 3, 2022 22:17
Show Gist options
  • Save liconti/2426617 to your computer and use it in GitHub Desktop.
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
<?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();
}
}
?>
@gskema
Copy link

gskema commented Apr 30, 2015

if(substr($temp_cache, -1) !== DIRECTORY_SEPARATOR) can be rewritten as rtrim($x, DIRECTORY_SEPARATOR)

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment