PHP 5.2.0+ 內建 ZipArchive 類提供完整的 ZIP 壓縮檔操作 API,無需外部工具。本文系統整理核心方法、錯誤碼對照、實戰範例(解壓、建立、追加、資料夾打包、刪除條目、註釋管理)。
php.ini 開啟 extension=php_zip.dll--enable-zip 或安裝 php-zip 套件| 方法 | 說明 | 回傳值 |
|---|---|---|
open(filename, flags) | 開啟/建立 ZIP 檔 | true / 錯誤碼 |
close() | 關閉並寫入磁碟 | bool |
extractTo(path) | 解壓至目錄 | bool |
addFile(filepath, localname) | 加入檔案 | bool |
addFromString(name, content) | 從字串建立檔案 | bool |
addEmptyDir(dirname) | 建立空目錄 | bool |
getNameIndex(index) | 取得索引對應檔名 | string/false |
getStream(name) | 取得檔案資料流 | resource/false |
renameIndex(index, newname) | 按索引重命名 | bool |
renameName(name, newname) | 按檔名重命名 | bool |
deleteIndex(index) | 按索引刪除條目 | bool |
deleteName(name) | 按檔名刪除條目 | bool |
getArchiveComment() | 取得壓縮檔註釋 | string |
setArchiveComment(comment) | 設定壓縮檔註釋 | bool |
getCommentIndex(index) | 取得檔案條目註釋 | string |
getCommentName(name) | 取得檔案條目註釋 | string |
| 常數 | 行為 |
|---|---|
ZipArchive::OVERWRITE | 總是建立新檔,存在則覆蓋 |
ZipArchive::CREATE | 不存在則建立(預設行為) |
ZipArchive::EXCL | 存在則報錯 |
ZipArchive::CHECKCONS | 檢查一致性 |
ER_EXISTS // 檔案已存在
ER_INCONS // 壓縮檔不一致
ER_INVAL // 無效參數
ER_MEMORY // 記憶體失敗
ER_NOENT // 檔案不存在
ER_NOZIP // 非 ZIP 檔
ER_OPEN // 無法開啟
ER_READ // 讀取錯誤
ER_SEEK // 定位錯誤
$zip = new ZipArchive();
$res = $zip->open('test.zip');
if ($res === TRUE) {
$zip->extractTo('test/'); // 解壓到 test 目錄
$zip->close();
echo '解壓成功';
} else {
echo '失敗,錯誤碼: ' . $res;
}
$zip = new ZipArchive();
$res = $zip->open('backup.zip', ZipArchive::CREATE | ZipArchive::OVERWRITE);
if ($res === TRUE) {
$zip->addFile('data.csv', 'export/data.csv'); // 實體檔案
$zip->addFromString('readme.txt', '說明內容...'); // 字串內容
$zip->addEmptyDir('empty_folder/'); // 空目錄
$zip->close();
echo '建立成功';
}
function zipFolder($folder, $zipFile) {
$zip = new ZipArchive();
if ($zip->open($zipFile, ZipArchive::CREATE | ZipArchive::OVERWRITE) !== TRUE) {
return false;
}
$rootPath = realpath($folder);
$files = new RecursiveIteratorIterator(
new RecursiveDirectoryIterator($rootPath),
RecursiveIteratorIterator::LEAVES_ONLY
);
foreach ($files as $name => $file) {
if (!$file->isDir()) {
$filePath = $file->getRealPath();
$relativePath = substr($filePath, strlen($rootPath) + 1);
$zip->addFile($filePath, $relativePath);
} else {
$relativePath = substr($name, strlen($rootPath) + 1) . '/';
$zip->addEmptyDir($relativePath);
}
}
return $zip->close();
}
zipFolder('/var/www/project', '/backup/project_' . date('Ymd') . '.zip');
$zip = new ZipArchive();
if ($zip->open('test.zip') === TRUE) {
$stream = $zip->getStream('hello.txt');
$content = stream_get_contents($stream);
echo $content; // 注意編碼轉換
$zip->close();
}
$zip = new ZipArchive();
$res = $zip->open('test.zip', ZipArchive::CREATE);
if ($res === TRUE) {
$zip->setArchiveComment('Updated at ' . date('Y-m-d H:i:s'));
$zip->close();
}
$zip = new ZipArchive();
if ($zip->open('test.zip') === TRUE) {
$zip->deleteName('obsolete.txt'); // 或 deleteIndex(0)
$zip->close();
}
setEncryptionIndex()ZipArchive 以物件導向 API 封裝 libzip,功能完整、效能優異,是 PHP 專案處理壓縮檔的首選方案。