【发布时间】:2016-01-27 02:01:23
【问题描述】:
我尝试使用 zip 存档创建一个 zip 文件,尽管该 zip 文件同时在两个不同的文件夹中下载了两次,即源代码所在的 htdocs 文件夹和浏览器设置中的默认下载文件夹,但它工作正常。有什么办法可以防止这种情况发生吗?我只希望它被下载一次到下载文件夹中......
$file_names = explode(',', $_REQUEST['files']);
$dir = $_REQUEST['currentdir'];
//Archive name
$archive_file_name="Downloaded_".date("Y-m-d_G-i-s").".zip";
//Download Files path
$file_path=$dir;
//cal the function
zipFilesAndDownload($file_names,$archive_file_name,$file_path);
function zipFilesAndDownload($file_names,$archive_file_name,$file_path)
{
$zip = new ZipArchive();
$res = $zip->open($archive_file_name, ZIPARCHIVE::CREATE | ZIPARCHIVE::OVERWRITE );
if ($res===TRUE) {
//add each files of $file_name array to archive
foreach($file_names as $files)
{
$tt=$file_path."/".$files;
if (file_exists($tt)){
$zip->addFile($tt,$files);
}
else{
return false;
exit;
}
}
$zip->close();
//then send the headers to force download the zip file
header('Content-type: application/zip');
header("Content-Disposition: attachment; filename=\"".basename($archive_file_name)."\"");
header('Pragma: no-cache');
header('Expires: 0');
//header('Content-Length: ' . filesize($archive_file_name));
ob_end_clean();
//flush();
readfile($archive_file_name);
exit;
}
else{
return false;
exit;
}
}
【问题讨论】:
-
您在 htdocs 文件夹中创建 zip(PHP 将其保存在那里),这就是它存在的原因。您只需下载一次。
-
代码必须在 htdocs 中才能运行,因为我所有的 php 代码都在 htdocs 中运行...有什么代码或方法可以阻止它生成文件到 htdocs 中吗?
-
您可以使用在文件名前添加一个目录名,然后将其保存在该目录中。
标签: php download readfile ziparchive