php.ini 啟用 extension=zip(Windows 取消 php_zip.dll 註解)| 方法 | 說明 | 回傳值 |
|---|---|---|
open($filename, $flags) | 開啟/建立 ZIP 檔 | true 或錯誤碼 |
extractTo($path) | 解壓至指定目錄 | bool |
addFile($path, $name) | 加入實體檔案 | bool |
addFromString($name, $content) | 從字串建立檔案 | bool |
addEmptyDir($dirname) | 建立空目錄 | bool |
deleteIndex($index) | 按索引刪除項目 | bool |
deleteName($name) | 按名稱刪除項目 | bool |
renameIndex($index, $newName) | 按索引重命名 | bool |
renameName($oldName, $newName) | 按名稱重命名 | bool |
getNameIndex($index) | 取得索引對應檔名 | string|false |
getStream($name) | 取得檔案資源串流 | resource|false |
setArchiveComment($comment) | 設定 ZIP 檔註解 | bool |
getArchiveComment() | 取得 ZIP 檔註解 | string |
close() | 關閉並寫入變更 | bool |
ZipArchive::OVERWRITE // 總是建立新檔,覆蓋既有
ZipArchive::CREATE // 不存在則建立
ZipArchive::EXCL // 存在則報錯
ZipArchive::CHECKCONS // 檢查一致性
<?php
$zip = new ZipArchive();
$res = $zip->open('package.zip');
if ($res === true) {
$zip->extractTo('/var/www/uploads/extracted/');
$zip->close();
echo '解壓完成';
} else {
echo "開啟失敗,錯誤碼: $res";
}
?>
<?php
$zip = new ZipArchive();
$res = $zip->open('backup.zip', ZipArchive::CREATE | ZipArchive::OVERWRITE);
if ($res === true) {
$zip->addFile('/data/config.yaml', 'config.yaml');
$zip->addFile('/data/database.sql', 'db/backup.sql');
$zip->addFromString('readme.txt', '此為自動備份,建立時間: ' . date('c'));
$zip->close();
echo '備份建立成功';
} else {
echo "建立失敗: $res";
}
?>
<?php
function zipDirectory($source, $zip, $basePath = '') {
$source = rtrim($source, '/') . '/';
$basePath = $basePath ? rtrim($basePath, '/') . '/' : '';
$iterator = new RecursiveIteratorIterator(
new RecursiveDirectoryIterator($source, RecursiveDirectoryIterator::SKIP_DOTS),
RecursiveIteratorIterator::SELF_FIRST
);
foreach ($iterator as $file) {
$relativePath = $basePath . substr($file->getPathname(), strlen($source));
if ($file->isDir()) {
$zip->addEmptyDir($relativePath);
} else {
$zip->addFile($file->getPathname(), $relativePath);
}
}
}
$zip = new ZipArchive();
$zip->open('project.zip', ZipArchive::CREATE);
zipDirectory('/var/www/my-project', $zip, 'my-project/');
$zip->close();
?>
<?php
$zip = new ZipArchive();
if ($zip->open('data.zip') === true) {
$stream = $zip->getStream('config.json');
if ($stream) {
$content = stream_get_contents($stream);
fclose($stream);
$config = json_decode($content, true);
print_r($config);
}
$zip->close();
}
?>
<?php
$zip = new ZipArchive();
if ($zip->open('archive.zip') === true) {
// 依索引重命名
$zip->renameIndex(0, 'new_first_file.txt');
// 依名稱重命名
$zip->renameName('old_name.jpg', 'new_name.jpg');
$zip->close();
}
?>
ER_EXISTS 檔案已存在
ER_INCONS ZIP 檔不一致/損壞
ER_INVAL 無效參數
ER_MEMORY 記憶體配置失敗
ER_NOENT 檔案不存在
ER_NOZIP 非 ZIP 檔案
ER_OPEN 無法開啟檔案
ER_READ 讀取錯誤
ER_SEEK 定位錯誤
ZipArchive 需將整個 ZIP 結構載入記憶體,超過 2GB 檔案建議改用 exec('zip ...') 呼叫系統指令ZipArchive::setEncryptionName() 支援 AES-256 加密(需 libzip 1.2.0+)close() 並重新 open() 釋放記憶體addFile() 不保留 Unix 權限位,需自行記錄並在解壓後 chmod()ZipArchive 是 PHP 內建最完整的 ZIP 操作介面,掌握上述核心方法即可應對 95% 的壓縮解壓需求,無需引入第三方函式庫。