以下是一个使用PHP递归函数对目录进行压缩打包的示例代码:
<?php
function zipDirectory($source, $destination)
{
if (!extension_loaded('zip') || !file_exists($source)) {
return false;
}
$zip = new ZipArchive();
if (!$zip->open($destination, ZIPARCHIVE::CREATE)) {
return false;
}
$source = str_replace('\\', '/', realpath($source));
if (is_dir($source) === true) {
$files = new RecursiveIteratorIterator(new RecursiveDirectoryIterator($source), RecursiveIteratorIterator::SELF_FIRST);
foreach ($files as $file) {
$file = str_replace('\\', '/', $file);
if (in_array(substr($file, strrpos($file, '/') + 1), array('.', '..'))) {
continue;
}
$file = realpath($file);
if (is_dir($file) === true) {
$zip->addEmptyDir(str_replace($source . '/', '', $file . '/'));
} else if (is_file($file) === true) {
$zip->addFromString(str_replace($source . '/', '', $file), file_get_contents($file));
}
}
} else if (is_file($source) === true) {
$zip->addFromString(basename($source), file_get_contents($source));
}
return $zip->close();
}
// 用法示例
$source = '/path/to/sourceDirectory';
$destination = '/path/to/destinationArchive.zip';
if (zipDirectory($source, $destination)) {
echo 'Directory successfully compressed and packed into ' . $destination;
} else {
echo 'Failed to compress directory';
}
请确保在执行此代码之前已经安装了PHP的Zip扩展。您可以将$source
替换为您要打包的目录的路径,将$destination
替换为打包文件的保存路径。执行代码后,将会将目录压缩打包成一个zip文件。