Zip文件未在PHP中下载
Posted
技术标签:
【中文标题】Zip文件未在PHP中下载【英文标题】:Zip file not downloading in PHP 【发布时间】:2013-12-23 10:24:00 【问题描述】:我已经实现了创建压缩文件文件夹(从 db 路径)并在 php 中下载压缩文件夹的代码。我正在使用 Ubuntu 操作系统。
public function actionDownload($id)
$model = $this->loadModel($id, 'Document');
$results = array();
$results = $this->createZip($model);
$zip = $results[0];
$size = filesize($zip->filename);
if ($zip->filename)
header("Content-Description: File Transfer");
header("Content-type: application/zip");
header("Content-Disposition: attachment; filename=\"" . $model->name . "\"");
header("Content-Transfer-Encoding: binary");
header("Content-Length: " . $size);
ob_end_flush();
flush();
readfile($zip->filename);
// To Store User Transaction Data
//$this->saveTransaction();
//ignore_user_abort(true);
unlink($zip->filename);
$zip->close();
// Delete newly created files
foreach ($results[1] as $fl)
unlink($fl);
public function createZip($model)
$data = Document::model()->findAll('parent_folder=:id', array(':id' => (int) $model->document_id));
$fileArr = array();
foreach ($data as $type)
$fileArr[] = $type->path;
$filestozip = $fileArr; // FILES ARRAY TO ZIP
$path = Yii::app()->basePath . DS . 'uploads' . DS . Yii::app()->user->id;
//$model->path = trim(DS . $path . DS); // DIR NAME TO MOVE THE ZIPPED FILES
$zip = new ZipArchive();
$files = $filestozip;
$zipName = "USR_" . Yii::app()->user->id . "_" . $model->name . "_" . date("Y-m-d") . ".zip";
$fizip = $path . DS . $zipName;
if ($zip->open($fizip, ZipArchive::CREATE) === TRUE)
foreach ($files as $fl)
if (file_exists($fl))
$zip->addFile($fl, basename($fl)) or die("<p class='warning'>ERROR: Could not add file: " . $fl . "</p>");
$resultArr = array();
$resultArr[] = $zip;
$resultArr[] = $files;
return $resultArr;
Zip 创建代码工作正常,它在那里创建 zip 文件,但问题是文件的所有者是 www-data 并且文件权限是 只读。
当我尝试为该压缩文件夹设置chmod($zip->filename, 0777)
权限时,它会显示错误?
Error 500
chmod(): No such file or directory
事实上文件在那里。
如果我在没有chmod()
的情况下尝试,那么它会显示错误
Error 500
filesize(): stat failed for /home/demo.user/myapp/public_html/backend/uploads/1/USR_1_kj_2013-12-23.zip
然后它没有下载 zip 文件。
这是我面临的非常奇怪的问题。这似乎是 zip 文件的一些权限问题,这就是为什么 filesize()
无法对该文件执行任何操作但奇怪的是 chmod()
也无法正常工作。
需要这方面的帮助。
谢谢
【问题讨论】:
【参考方案1】:如果www-data
具有读取权限,则文件权限设置正确。不需要chmod
。
您需要在下载之前调用$zip->close()
,因为只有在$zip->close()
上,文件才会写入磁盘。除非将文件写入磁盘,否则readfile()
将不起作用。
更聪明的方法是仅使用php://memory
流包装器在内存中创建存档。但是,如果您只需要一次下载的存档,这只是一种选择。
【讨论】:
文件夹已经拥有读写权限,但是当 PHP 在该文件夹中创建 zip 文件时,它没有读写权限 您添加了$zip->close
吗?它会返回true
吗?
Yes $zip->close() 如果我在下载前使用它会返回空白页
是的,我明白了。它必须在下载之前。在createZip()
我应该在哪里写 zip->close() ?你能指导我吗?以上是关于Zip文件未在PHP中下载的主要内容,如果未能解决你的问题,请参考以下文章