萬盛學電腦網

您现在的位置: 萬盛學電腦網 >> 程式設計 >  >> 網路程式設計 >> PHP 程式設計

PHP ZipArchive 創建 ZIP 壓縮包:文件列表打包、路徑控制、大文件分卷完整實戰

PHP 內建 ZipArchive 類提供原生 ZIP 壓縮能力,無需外部命令。本文封裝一個 ZipFile 類:支援文件列表添加、自定義壓縮包內路徑、MD5 內容去重、流式寫入大文件、分卷壓縮策略建議。

核心類實現

class ZipFile {
    private ZipArchive $zip;
    private array $files = [];
    private string $outputPath;
    private string $basePath; // 源文件基準路徑,用於計算相對路徑

    public function __construct(string $outputPath, string $basePath = '') {
        $this->outputPath = $outputPath;
        $this->basePath = rtrim($basePath, '/\\');
        $this->zip = new ZipArchive();
    }

    public function addFile(string $absolutePath, string $insidePath = ''): self {
        if (!is_file($absolutePath)) throw new InvalidArgumentException("文件不存在: $absolutePath");
        $insidePath = $insidePath ?: ($this->basePath ? ltrim(str_replace($this->basePath, '', $absolutePath), '/\\') : basename($absolutePath));
        $this->files[] = [$absolutePath, $insidePath];
        return $this;
    }

    public function addFiles(array $absolutePaths, string $commonPrefix = ''): self {
        foreach ($absolutePaths as $p) $this->addFile($p, $commonPrefix ? ltrim(str_replace($commonPrefix, '', $p), '/\\') : '');
        return $this;
    }

    public function create(int $flags = 0): string {
        $openFlags = ZipArchive::CREATE | ZipArchive::OVERWRITE | $flags;
        if ($this->zip->open($this->outputPath, $openFlags) !== true) {
            throw new RuntimeException("無法創建 ZIP: {$this->outputPath}, 錯誤碼: " . $this->zip->getStatusString());
        }
        foreach ($this->files as [$abs, $inside]) {
            if (!$this->zip->addFile($abs, $inside)) {
                throw new RuntimeException("添加文件失敗: $abs -> $inside");
            }
        }
        if (!$this->zip->close()) {
            throw new RuntimeException("關閉 ZIP 失敗: " . $this->zip->getStatusString());
        }
        return $this->outputPath;
    }

    // 靜態快捷方法
    public static function quickCreate(string $output, array $files, string $basePath = ''): string {
        return (new self($output, $basePath))->addFiles($files)->create();
    }
}

使用範例

// 1. 單文件指定內部路徑
ZipFile::quickCreate('dist/app.zip', [
    '/var/www/html/index.php' => 'public/index.php',
    '/var/www/html/config/.env' => 'config/.env',
]);

// 2. 整個目錄遞歸打包(保持相對結構)
$files = new RecursiveIteratorIterator(new RecursiveDirectoryIterator('/var/www/html', FilesystemIterator::SKIP_DOTS));
$fileList = [];
foreach ($files as $file) {
    if ($file->isFile()) $fileList[] = $file->getPathname();
}
ZipFile::quickCreate('dist/full_backup.zip', $fileList, '/var/www/html');

// 3. 大文件分卷策略(ZipArchive 不原生支援分卷)
// 方案 A:生成單一 ZIP 再用 `split -b 100M` 分割(Linux)
// 方案 B:使用 PclZip / ZipStream-PHP 支援流式分卷輸出
// 方案 C:改用 7z 命令行 `7z a -v100m backup.7z dir/`(壓縮率更高、原生分卷)

大文件/高併發優化

  • 流式寫入:ZipStream\ZipStream 直接輸出到 HTTP 響應流,無臨時文件,支援下載即壓縮。
  • 並行壓縮:將文件列表分片,多進程各自創建部分 ZIP,最後合併(需中央目錄合併邏輯)。
  • 排除無用文件:.git、node_modules、vendor、*.log、.env 等通過 RecursiveRegexIterator 過濾。
  • 權限保留:ZipArchive::setExternalAttributes 設置 Unix 權限位(需 PHP 7.1+)。

安全與合規

  1. 路徑遍歷防護:$insidePath 必須標準化,禁止 ../、絕對路徑、符號鏈接逃逸。
  2. 文件類型驗證:壓縮前掃描可執行文件、腳本、Webshell 特徵。
  3. 密碼保護:ZipArchive::setEncryptionName (PHP 7.2+) 支援 AES-256 加密,但兼容性一般(Windows 資源管理器需額外工具解壓),建議 7z AES-256。

ZipArchive 適合中小型打包任務;GB 級以上、分卷、加密、高併發場景請評估 ZipStream-PHP、7z、libarchive 等專業工具鏈。

copyright © 萬盛學電腦網 all rights reserved