[英]Invalid or unitialized Zip object
if(isset($_POST['items'])) {
// open zip
$zip_path = 'downloadSelected/download.zip';
$zip = new ZipArchive();
if ($zip->open($zip_path, ZIPARCHIVE::CREATE | ZIPARCHIVE::OVERWRITE) !== TRUE) {
die ("An error occurred creating your ZIP file.");
}
foreach ($_POST['items'] as $path) {
// generate filename to add to zip
$filepath = 'downloads/' . $path . '.zip';
if (file_exists($filepath)) {
$zip->addFile($filepath, $path . '.zip') or die ("ERROR: Could not add the file $filename");
}
else {
die("File $filepath doesnt exit");
}
$zip->close();
} }
我收到警告: ZipArchive::addFile()
[function.ZipArchive-addFile]: Invalid or unitialized Zip object 。 可能有什么問題? 我嘗試了很多方法,但徒勞無功。 當我選擇一個文件時,我能夠創建和啟動下載。 但是,當我選擇多個文件時,出現上述錯誤。
正確縮進的力量!
您正在關閉循環中的 zip 文件。
如果我重新格式化您的代碼,它變得顯而易見。
更正后的代碼如下:
if(isset($_POST['items'])) {
// open zip
$zip_path = 'downloadSelected/download.zip';
$zip = new ZipArchive();
if ($zip->open($zip_path, ZIPARCHIVE::CREATE | ZIPARCHIVE::OVERWRITE) !== TRUE) {
die ("An error occurred creating your ZIP file.");
}
foreach ($_POST['items'] as $path) {
// generate filename to add to zip
$filepath = 'downloads/' . $path . '.zip';
if (file_exists($filepath)) {
$zip->addFile($filepath, $path . '.zip') or die ("ERROR: Could not add the file $filename");
} else {
die("File $filepath doesnt exit");
}
}
$zip->close();
}
庫本身為您提供了一個代碼來查看它失敗的原因:
$ZIP_ERROR = [
ZipArchive::ER_EXISTS => 'File already exists.',
ZipArchive::ER_INCONS => 'Zip archive inconsistent.',
ZipArchive::ER_INVAL => 'Invalid argument.',
ZipArchive::ER_MEMORY => 'Malloc failure.',
ZipArchive::ER_NOENT => 'No such file.',
ZipArchive::ER_NOZIP => 'Not a zip archive.',
ZipArchive::ER_OPEN => "Can't open file.",
ZipArchive::ER_READ => 'Read error.',
ZipArchive::ER_SEEK => 'Seek error.',
];
$result_code = $zip->open($zip_fullpath);
if( $result_code !== true ){
$msg = isset($ZIP_ERROR[$result_code])? $ZIP_ERROR[$result_code] : 'Unknown error.';
return ['error'=>$msg];
}
根據文檔你不能或打開模式標志,你只能在一種模式下打開。 首先檢查文件是否存在並適當地設置打開模式,看看是否有幫助。
您也可能使用php://output
作為文件名(不是針對問題作者,而是針對搜索此錯誤的任何人),ZipArchive 不支持這種情況。
如果您需要輸出 zip 文件,請將其保存到臨時文件,然后使用readfile
功能。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.