<?php
require_once './include/zip.php';
$zip = new PHPZip();
// 僅生成不下載
// $zip->createZip('要壓縮的資料夾路徑', '輸出檔名.zip');
// 直接打包並觸發瀏覽器下載
$zip->downloadZip('要壓縮的資料夾路徑', '輸出檔名.zip');
?>
<?php
require_once './include/zip.php';
if (!$download) exit();
set_time_limit(60);
// 假設從 checkbox 取得選項
$tempDir = sys_get_temp_dir() . '/zip_' . session_id();
@mkdir($tempDir, 0777, true);
// 複製選取的檔案與資料夾到暫存區 (需自行實作 TmpManager)
$tmpManager = new TmpManager();
$tmpManager->CopyFile($selectedFiles, $tempDir);
$tmpManager->CopyFolder($selectedFolders, $tempDir);
// 打包下載
$zip = new PHPZip();
$zip->downloadZip($tempDir, 'files_' . date('Ymd') . '.zip');
// 事後可註冊 shutdown function 清理暫存目錄
register_shutdown_function(function() use ($tempDir) {
$tmpManager->DeleteDir($tempDir);
});
?>
gzcompress() 壓縮資料 (需 zlib 擴充)dirTree())unix2DosTime())ZipArchive 內建類別<?php
function createZip(string $sourceDir, string $outputFile): bool
{
$zip = new ZipArchive();
if ($zip->open($outputFile, ZipArchive::CREATE | ZipArchive::OVERWRITE) !== true) {
return false;
}
$files = new RecursiveIteratorIterator(
new RecursiveDirectoryIterator($sourceDir, FilesystemIterator::SKIP_DOTS),
RecursiveIteratorIterator::SELF_FIRST
);
foreach ($files as $file) {
$relativePath = substr($file->getPathname(), strlen($sourceDir) + 1);
if ($file->isDir()) {
$zip->addEmptyDir($relativePath);
} else {
$zip->addFile($file->getPathname(), $relativePath);
}
}
return $zip->close();
}
// 使用
$tmpZip = tempnam(sys_get_temp_dir(), 'zip_');
createZip('/path/to/folder', $tmpZip);
header('Content-Type: application/zip');
header('Content-Disposition: attachment; filename="backup.zip"');
readfile($tmpZip);
unlink($tmpZip);
優點:C 層實作效能極佳、支援大檔案、標準庫無相依、語法簡潔。