>我正在尝试制作一个表单,用户可以在其中选择他们想要的PDF手册,并将其压缩为文件名"Brochures.zip"供他们下载。
我有问题要解决这个问题。谁能强调哪里出了问题?谢谢!
形式:
<label><input type="checkbox" name="brochure[]" value="file1">file1</label>
<label><input type="checkbox" name="brochure[]" value="file2">file2</label>
<label><input type="checkbox" name="brochure[]" value="file3">file3</label>
<label><input type="checkbox" name="brochure[]" value="file4">file4</label>
下载.php
$brochure = $_POST['brochure'] ;
$send = true;
if($send) {
$zip = new ZipArchive();
$res = $zip->open('download.zip', ZipArchive::CREATE);
if ($res === TRUE) {
foreach ($brochure as $file => $val) {
$filename = '../pdf/' . $val . '.pdf';
$zip->addFile($filename);
}
$zip->close();
header('Content-type: application/zip');
header('Content-Disposition: attachment; filename="download.zip"');
readfile('download.zip');
}else {
echo 'failed';
}
如果文件未添加到存档中,您可以添加一个简单的检查:
if (!file_exists($filename)) { die("Cannot find $filename"); }
您还可以增加错误报告:
error_reporting(-1);
ini_set('display_errors', 'On');
然后在$zip->close();
之后立即exit;
. 如果出现任何问题,$zip->addFile()
应该返回false
,所以希望它也会显示一些警告/错误。
您也可以尝试使用file_get_contents()
addFromString()
,看看是否有帮助。我的猜测是,包含 ..
的相对路径会抛弃 Zip 扩展名。
这是目录结构。
-
.PDF
-- 文件1.pdf
-- 文件2.pdf
-- 文件3.pdf
-
.zip
-- 创建.php
-- 下载.php
下面是与您的代码相同的代码...
创建.php
<form action="download.php" method="post">
<label><input type="checkbox" name="brochure[]" value="file1">file1</label>
<label><input type="checkbox" name="brochure[]" value="file2">file2</label>
<label><input type="checkbox" name="brochure[]" value="file3">file3</label>
<label><input type="checkbox" name="brochure[]" value="file4">file4</label>
<input type="submit">
</form>
下载.php与上面的代码相同。确保您具有正确的目录结构。正如我所说,我尝试了您的代码,它按预期工作,使用选定的文件(如 file1.pdf、file2.pdf 等创建下载.zip文件......
我设法通过使用此处的脚本来解决问题。另外,我意识到我需要将具有权限的文件夹设置为 757,然后才能生成 zip 文件。