[英]Codeigniter Zip directory and download
在压缩目录并尝试使用codeigniter下载时,我遇到了一个非常奇怪的问题。
这是代码
$this->load->library('zip'); //Loading the zip library
$directory = $_SESSION['directory-download-path']; //Getting the directory from session
$name = basename($directory); //get the name of the folder
$name = str_replace(" ", "_", $name).".zip"; //create the zip name
unset($_SESSION['directory-download-path']); //removing it from session
$this->zip->read_dir($directory); //read the directory
$this->zip->download($name); //download the zip
这很简单。 下载出现问题。 我得到了zip文件,但是当我提取它时,我得到了一个带有.zip.cpgz的文件,并继续提取相似的文件。 因此,我认为它已损坏。 您能帮我为什么会这样吗? 我具有目录上的所有权限,因为我正在执行其他操作。
编辑:
经过更多研究,我发现添加第二个参数如下:
$this->zip->read_dir($directory, false); //read the directory
但仍然无法正常工作。 另一个解决方案是添加
ob_end_clean();
就在该行之前: $this->zip->download($name); //download the zip
$this->zip->download($name); //download the zip
但还是没有成功!
由于我没有响应,因此我在codeigniter之外做了一个函数,该函数以递归方式压缩文件和文件夹,如下所示:
public function Zip($source, $destination)
{
if (!extension_loaded('zip') || !file_exists($source)) {
return false;
}
$zip = new ZipArchive();
if (!$zip->open($destination, ZIPARCHIVE::CREATE)) {
return false;
}
$source = str_replace('\\', '/', realpath($source));
if (is_dir($source) === true)
{
$files = new RecursiveIteratorIterator(new RecursiveDirectoryIterator($source), RecursiveIteratorIterator::SELF_FIRST);
foreach ($files as $file)
{
$file = str_replace('\\', '/', $file);
if( in_array(substr($file, strrpos($file, '/')+1), array('.', '..', "Thumbs.db")) )
continue;
$file = realpath($file);
if (is_dir($file) === true)
{
$zip->addEmptyDir(str_replace($source . '/', '', $file . '/'));
}
else if (is_file($file) === true)
{
$zip->addFromString(str_replace($source . '/', '', $file), file_get_contents($file));
}
}
}
else if (is_file($source) === true)
{
$zip->addFromString(basename($source), file_get_contents($source));
}
return $zip->close();
}
之后,在codeigniter控制器中,我这样做了:
$this->projects->Zip($source, $destination);
header("Content-type: application/zip");
header("Content-Disposition: attachment; filename=$name");
header("Content-length: " . filesize($destination));
header("Pragma: no-cache");
header("Expires: 0");
readfile($destination);
unlink($destination);
当然, $destination
应该位于您拥有777或等同权限的临时文件夹中,以便在文件发送到客户端时将其删除。
希望这可以帮助!
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.