以下是一個使用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文件。