PclZip 是純 PHP 實現的 ZIP 壓縮/解壓縮庫,無需額外擴展即可運行,功能強大且 API 直觀。本文詳細說明建立壓縮檔、列出內容、解壓縮、路徑處理等核心操作,並解析其靈活的選項參數設計。
<?php
include_once 'pclzip.lib.php';
$archive = new PclZip('archive.zip');
// 方式一:直接壓縮檔案/目錄(保留相對路徑)
$v_list = $archive->create('file.txt, data/text.txt, folder');
if ($v_list == 0) {
die('Error: ' . $archive->errorInfo(true));
}
// 方式二:進階路徑控制
$v_list = $archive->create(
'data/file.txt, data/text.txt', // 來源檔案
PCLZIP_OPT_REMOVE_PATH, 'data', // 移除來源路徑前綴 'data/'
PCLZIP_OPT_ADD_PATH, 'install' // 加上新前綴 'install/'
);
if ($v_list == 0) {
die('Error: ' . $archive->errorInfo(true));
}
?>
PclZip 採用 常數 + 值成對出現 的可變參數設計,極具彈性:
| 常數 | 用途 | 說明 |
|---|---|---|
PCLZIP_OPT_REMOVE_PATH | 移除路徑前綴 | 字串或陣列,從來源路徑移除指定前綴 |
PCLZIP_OPT_ADD_PATH | 添加路徑前綴 | 壓縮包內檔案將置於此虛擬目錄下 |
PCLZIP_OPT_PATH | 設定解壓縮目標目錄 | 配合 extract() 使用 |
PCLZIP_OPT_EXTRACT_AS_STRING | 解壓至字串變數 | 不寫入磁碟,直接返回內容 |
PCLZIP_OPT_BY_NAME | 按檔名篩選 | 僅處理指定檔名 |
PCLZIP_OPT_BY_EREG | 正則篩選 | 僅處理符合正則的檔案 |
PCLZIP_OPT_REPLACE_NEWER | 僅替較新檔案 | 解壓時保留較新版本 |
PCLZIP_OPT_STOP_ON_ERROR | 錯誤即停止 | 預設繼續處理 |
PCLZIP_OPT_TEMP_DIR | 指定臨時目錄 | 大檔案處理時避免預設目錄空間不足 |
PCLZIP_OPT_COMMENT | 設定壓縮包註解 | 字串 |
PCLZIP_OPT_PREPEND_COMMENT | 前綴註解 | 追加至現有註解 |
$list = $archive->listContent();
if ($list == 0) die('Error: ' . $archive->errorInfo(true));
foreach ($list as $file) {
echo "{$file['filename']} | {$file['stored_filename']} | "
. "大小: {$file['size']} | 壓縮後: {$file['compressed_size']} | "
. "時間: " . date('Y-m-d H:i:s', $file['mtime']) . "
";
}
$list = $archive->extract(
PCLZIP_OPT_PATH, 'extract_folder/',
PCLZIP_OPT_REPLACE_NEWER
);
if ($list == 0) die('Error: ' . $archive->errorInfo(true));
$content = $archive->extract(
PCLZIP_OPT_BY_NAME, 'config.php',
PCLZIP_OPT_EXTRACT_AS_STRING
);
if ($content == 0) die('Error: ' . $archive->errorInfo(true));
echo $content[0]['content']; // 直接取得檔案內容
$list = $archive->delete(PCLZIP_OPT_BY_NAME, 'old.txt');
$props = $archive->properties();
echo "檔案數: {$props['nb']} | 總大小: {$props['size']} | 註解: {$props['comment']}";
if ($result == 0) {
// 詳細錯誤資訊
$error = $archive->errorInfo(true); // true = 返回陣列, false = 返回字串
echo "代碼: {$error['code']} | 訊息: {$error['message']}";
}
memory_limit,需分批或調整配置。ZipArchive + setPassword() (PHP 7.2+)。| 庫/擴展 | 類型 | 優點 | 缺點 |
|---|---|---|---|
ZipArchive | C 擴展 | 速度快、支援 ZIP64/AES、原生串流 | 需安裝擴展、API 較底層 |
PclZip | 純 PHP | 零依賴、共享主機友善、API 高階 | 大檔案效能弱、無 AES |
nelexa/zip | 純 PHP (現代) | 支援 ZIP64/AES、PSR 標準、串流 | 相對較新、社區較小 |
chumper/zipper | Laravel 封裝 | 語法優雅、整合框架 | 依賴 ZipArchive |
PclZip 以零依賴、高階 API 成為共享主機、舊專案、快速原型的首選 ZIP 工具。理解其選項參數設計(常數+值成對),可靈活處理路徑重寫、篩選、串流等進階需求。新專案若環境允許,優先考慮 ZipArchive 或現代純 PHP 庫以獲得更好效能與安全性。