Skip to content

Instantly share code, notes, and snippets.

@frumbert
Created September 2, 2019 04:30
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save frumbert/10dc89c918e5ea20f18a58bff1f147fd to your computer and use it in GitHub Desktop.
Save frumbert/10dc89c918e5ea20f18a58bff1f147fd to your computer and use it in GitHub Desktop.
zip each folder in current directory recursively without the top-level folder, and name it after the directory
<?php
header("content-type:text/plain");
$root = realpath(".");
$ar = array_diff(scandir($root), array('.','..'));
foreach ($ar as $fold) {
$rootPath = "{$root}/{$fold}";
if (is_dir($rootPath)) {
$zip = new ZipArchive();
$zip->open("{$rootPath}.zip", ZipArchive::CREATE | ZipArchive::OVERWRITE);
$files = new RecursiveIteratorIterator(
new RecursiveDirectoryIterator($rootPath), RecursiveIteratorIterator::LEAVES_ONLY
);
foreach ($files as $name => $file) {
if (!$file->isDir()) {
$filePath = $file->getRealPath();
$relativePath = substr($filePath, strlen($rootPath) + 1);
$zip->addFile($filePath, $relativePath);
}
}
$zip->close();
echo "{$fold}.zip", PHP_EOL;
}
}
echo "Done.";
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment