问题描述
我正在尝试在 Internet 上找到的这段代码,它有助于使用 PHP 上的文件创建 ZipArchive。
我正在在我的服务器上尝试此操作,这是一个 AWS EC2 with Linux Ubuntu,其中运行 Web 服务器。我运行以下代码:
<?PHP
function createZipAndDownload($files,$filesPath,$zipFileName)
{
// Create instance of ZipArchive. and open the zip folder.
$zip = new ZipArchive();
$r = $zip->open($zipFileName,ZipArchive::CREATE);
var_dump($r); echo "<br>";
// Adding every attachments files into the ZIP.
foreach ($files as $file) {
$r = $zip->addFile($filesPath . $file,$file);
var_dump($r); echo "<br>";
}
$r = $zip->close();
var_dump($r); echo "<br>";
// Download the created zip file
header("Content-type: application/zip");
header("Content-disposition: attachment; filename = $zipFileName");
header("Content-length: " . filesize($zipFileName));
header("Pragma: no-cache");
header("Expires: 0");
readfile("$zipFileName");
exit;
}
// Files which need to be added into zip
$files = array('twiglet-1120x720.jpg','22vwqq.jpg','fb4eb7f8aa5431b0b4e26365ebd59933-239x300.jpg');
// Directory of files
$filesPath = 'https://peakon.com/wp-content/uploads/2018/08/';
// Name of creating zip file
$zipName = 'document.zip';
echo createZipAndDownload($files,$zipName);
?>
bool(true)
bool(false)
bool(false)
bool(false)
bool(true)
我知道 ZipArchive 已创建,但文件未在 ZipArchive 内发送。然而,文件一旦下载完成,当我想打开它时,上面写着“文件已损坏”,我无法打开它。
你能帮我吗?你知道为什么它不起作用吗?我想在里面插入这些图像并下载它? (图片仅供参考)
预先感谢您的帮助。
解决方法
addFile
采用文件系统路径,而不是 HTTP URL。有多种方法可以修复它,但对于您的情况,将 file_get_contents
与 addFromString
一起使用可能是最简单的。 file_get_contents
确实接受网址,这很奇怪。请注意,addFromString
的参数与 addFile
的顺序不同。
$r = $zip->addFromString($file,file_get_contents($filesPath . $file));
然而,从长远来看,我建议您下载文件,检查结果并根据需要抛出错误消息,但这至少应该让您开始。
编辑
参数 ZipArchive::CREATE
只会在存档不存在时创建存档,因此它实际上可能会尝试打开现有文件,而在您之前的尝试中,这可能会导致您打开损坏的文件。相反,我建议使用 ZipArchive::OVERWRITE
重新开始,或使用 ZipArchive::EXCL
来保证不会触及现有文件。
将所有这些放在一起,这段代码在我测试时完全按原样工作:
function createZipAndDownload($files,$filesPath,$zipFileName)
{
// Create instance of ZipArchive. and open the zip folder.
$zip = new ZipArchive();
$r = $zip->open($zipFileName,ZipArchive::OVERWRITE);
var_dump($r);
echo "<br>";
// Adding every attachments files into the ZIP.
foreach ($files as $file) {
$r = $zip->addFromString($file,file_get_contents($filesPath . $file));
var_dump($r);
echo "<br>";
}
$r = $zip->close();
var_dump($r);
echo "<br>";
// Download the created zip file
header("Content-type: application/zip");
header("Content-Disposition: attachment; filename = $zipFileName");
header("Content-length: " . filesize($zipFileName));
header("Pragma: no-cache");
header("Expires: 0");
readfile($zipFileName);
exit;
}
// Files which need to be added into zip
$files = array('twiglet-1120x720.jpg','22vwqq.jpg','fb4eb7f8aa5431b0b4e26365ebd59933-239x300.jpg');
// Directory of files
$filesPath = 'https://peakon.com/wp-content/uploads/2018/08/';
// Name of creating zip file
$zipName = 'document.zip';
createZipAndDownload($files,$zipName);