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();
} }
Run Code Online (Sandbox Code Playgroud)
我收到警告:ZipArchive::addFile()[function.ZipArchive-addFile]:Zip对象无效或单元化.可能有什么问题?我尝试了很多方法但是徒劳无功.当我选择一个文件时,我能够创建并启动下载.但是,当我选择多个文件时,我会遇到上述错误.
Rob*_*lie 12
正确缩进的力量!
您正在关闭循环中的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();
}
Run Code Online (Sandbox Code Playgroud)
Ale*_*lva 10
库本身为您提供了一个代码来查看它失败的原因:
$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];
}
Run Code Online (Sandbox Code Playgroud)