如何在不下载整个目录路径的情况下下载zip文件? (PHP)

时间:2012-07-01 00:32:16

标签: php download zip document-root

我有以下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

意思是我得到一个名为applications的文件夹,包含所有子文件夹,然后在所有子文件夹中我得到myStuff.zip。

如何在没有目录的情况下下载myStuff.zip

2 个答案:

答案 0 :(得分:1)

试试这个。

readfile(basename($file));

答案 1 :(得分:0)

好的,我使用此链接中的代码回答了我自己的问题: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文件处于运行状态,而不是像我在我的问题中那样尝试检索先前压缩的文件。