我有以下zip下载功能:
$file='myStuff.zip';
function downloadZip($file){
$file=$_SERVER["DOCUMENT_ROOT"].'/uploads/'.$file;
if (headers_sent()) {
echo 'HTTP header already sent';
}
else {
if (!is_file($file)) {
header($_SERVER['SERVER_PROTOCOL'].' 404 Not Found');
echo 'File not found';
} else if (!is_readable($file)) {
header($_SERVER['SERVER_PROTOCOL'].' 403 Forbidden');
echo 'File not readable';
} else {
header($_SERVER['SERVER_PROTOCOL'].' 200 OK');
header("Content-Type: application/zip");
header("Content-Transfer-Encoding: Binary");
header("Content-Length: ".filesize($file));
header("Content-Disposition: attachment; filename='"".basename($file)."'"");
readfile($file);
exit;
}
}
}
问题是当我调用这个函数时,我最终不仅下载了myStuff.zip,还下载了包含所有文件夹的完整目录路径。我在一台使用 XAMPP 的 Mac 上,所以这意味着我得到以下内容:
/applications/xampp/htdocs/uploads/myStuff.zip
这意味着我得到一个名为应用程序的文件夹,其中包含所有子文件夹,然后在所有子文件夹中我得到myStuff.zip。
如何下载没有目录的myStuff.zip
?
试试这个。
readfile(basename($file));
好的,我使用此链接中的代码回答了我自己的问题:http://www.travisberry.com/2010/09/use-php-to-zip-folders-for-download/
这是 PHP:
<?php
//Get the directory to zip
$filename_no_ext= $_GET['directtozip'];
// we deliver a zip file
header("Content-Type: archive/zip");
// filename for the browser to save the zip file
header("Content-Disposition: attachment; filename=$filename_no_ext".".zip");
// get a tmp name for the .zip
$tmp_zip = tempnam ("tmp", "tempname") . ".zip";
//change directory so the zip file doesnt have a tree structure in it.
chdir('user_uploads/'.$_GET['directtozip']);
// zip the stuff (dir and all in there) into the tmp_zip file
exec('zip '.$tmp_zip.' *');
// calc the length of the zip. it is needed for the progress bar of the browser
$filesize = filesize($tmp_zip);
header("Content-Length: $filesize");
// deliver the zip file
$fp = fopen("$tmp_zip","r");
echo fpassthru($fp);
// clean up the tmp zip file
unlink($tmp_zip);
?>
和 HTML:
<a href="zip_folders.php?directtozip=THE USERS DIRECTORY">Download All As Zip</a>
摆脱目录结构的关键步骤似乎是 chdir()
.还值得注意的是,此答案中的脚本使zip文件动态运行,而不是像我在问题中那样尝试检索以前压缩的文件。