PHP: How to access download folder outside root di

2019-03-05 16:49发布

问题:

This question already has an answer here:

  • Download files from server php 3 answers

How do I go about creating a PHP script/page that will allow members/buyers to download zipped files(products) stored in a download folder located outside root directory? I'm using Apache server. Please help!

Thanks! Paul G.

回答1:

I believe what you're trying to accomplish (stream an existing zip file via php) can be done similar to the answer here: LAMP: How to create .Zip of large files for the user on the fly, without disk/CPU thrashing


Slightly modified version of code from this answer:

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


回答2:

You might find some better info in the link provided by @soac, but here is an excerpt from some of my code for PDF files only:

<?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;
      }
?>

Note that this opens the PDF in the browser rather than downloading it perse, although you can save the file locally from within the reader. Using readfile() would probably be more efficient (and cleaner code) than the old way of opening the file via a handle the way I do in this example.

readfile($full_path);