首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> 網頁程式設計 >> PHP 程式設計 >> PHP 綜合知識

PHP 將資料夾打包為 ZIP 檔並提供下載

     編輯:PHP 綜合知識

使用第三方 PHPZip 類別

<?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);
});
?>

PHPZip 類別核心原理 (zip.php 摘要)

  • 手工組裝 ZIP 二進位格式:Local File Header + File Data + Central Directory + End of Central Directory
  • 使用 gzcompress() 壓縮資料 (需 zlib 擴充)
  • 支援目錄結構遞迴掃描 (dirTree())
  • 時間戳轉換為 DOS 格式 (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 層實作效能極佳、支援大檔案、標準庫無相依、語法簡潔。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved