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

时间:2013-05-09 21:47:58

标签: php apache download directory root

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

谢谢! 保罗G.

2 个答案:

答案 0 :(得分:1)

您可以在@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);

答案 1 :(得分:0)

我相信你想要完成的事情(通过php流式传输现有的zip文件)可以完成类似于这里的答案: LAMP: How to create .Zip of large files for the user on the fly, without disk/CPU thrashing


这个答案中稍微修改过的代码版本:

// 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);