PHP:如何访问根目录外的下载文件夹


PHP: How to access download folder outside root directory?

我如何去创建一个PHP脚本/页面,将允许成员/买家下载压缩文件(产品)存储在位于根目录外的下载文件夹?我使用Apache服务器。请帮助!

谢谢!保罗·g .

您可能会在@soac提供的链接中找到一些更好的信息,但这里是我的一些PDF文件代码的摘录:

<?php
      $file = ( !empty($_POST['file']) ? basename(trim($_POST['file'])) : '' );
      $full_path = '/dir1/dir2/dir3/'.$file;  // absolute physical path to file below web root.
      if ( file_exists($full_path) )
      {
         $mimetype = 'application/pdf';
         header('Cache-Control: no-cache');
         header('Cache-Control: no-store');
         header('Pragma: no-cache');
         header('Content-Type: ' . $mimetype);
         header('Content-Length: ' . filesize($full_path));
         $fh = fopen($full_path,"rb");
         while (!feof($fh)) { print(fread($fh, filesize($full_path))); }
         fclose($fh);
      }
      else
      {
         header("HTTP/1.1 404 Not Found");
         exit;
      }
?>

注意,这将在浏览器中打开PDF,而不是单独下载,尽管您可以从阅读器中本地保存文件。使用readfile()可能比我在这个例子中通过句柄打开文件的旧方法更有效(和更干净的代码)。

readfile($full_path);

我相信你想要完成的(通过php流式传输现有的zip文件)可以类似于这里的答案:LAMP:如何动态地为用户创建.Zip的大文件,而不需要磁盘/CPU抖动


根据这个答案稍微修改的代码版本:

// make sure to send all headers first
// Content-Type is the most important one (probably)
//
header('Content-Type: application/x-gzip');
$filename = "/path/to/zip.zip";
$fp = fopen($filename, "rb");
// pick a bufsize that makes you happy
$bufsize = 8192;
$buff = '';
while( !feof($fp) ) {
   $buff = fread($fp, $bufsize);
   echo $buff;
}
pclose($fp);