Link to home
Start Free TrialLog in
Avatar of luchuanc
luchuancFlag for United States of America

asked on

PHP - How to download a file from a secured web server folder

Hi,

How to to use php to  download a file from a secured web server folder?

Thanks,

Luchuan
Avatar of Ray Paseur
Ray Paseur
Flag of United States of America image

We may need to know a little more about what you mean by "secured", but here is the strategy I would follow.

Place the files in a location that is outside of the WWW root directory, so links to the files cannot exist.  The only way to get the files is to go through a downloader script.  A sample of the script is attached.  You can password protect this script and apply other rules - whatever your business rules need to be.

best regards, ~Ray
<?php // RAY_force_download.php
 
function force_download($filename)
{
   $basename = basename($filename);
   $filedata = file_get_contents($filename);
 
   if ($filedata)
   {
      header("Content-Type: application/force-download");
      header("Content-Disposition: attachment; filename=\"$basename\"");
      header("Content-length: ".(string)(strlen($filedata)));
      header("Expires: ".gmdate("D, d M Y H:i:s", mktime(date("H")+2, date("i"), date("s"), date("m"), date("d"), date("Y")))." GMT");
      header("Last-Modified: ".gmdate("D, d M Y H:i:s")." GMT");
      if (FALSE === strpos($_SERVER["HTTP_USER_AGENT"], 'MSIE 6'))
      {
         header("Cache-Control: no-cache, must-revalidate"); // OMIT FOR IE 6
      }
      header("Pragma: no-cache");
      flush();
      ob_start();
      echo $filedata;
   }
}
 
force_download("http://assets0.twitter.com/images/twitter.png");
 
?>

Open in new window

Avatar of luchuanc

ASKER

Hi Ray,
Thanks a lot for your help.
I tried the force_download script with my csv file on the web , it prints on the browser. Is it possible to let user pick a folder on their PC and download the file there?

Thanks,
Luchuan
ASKER CERTIFIED SOLUTION
Avatar of Ray Paseur
Ray Paseur
Flag of United States of America image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Thanks a lot,Ray,
Luchuan
Thanks for the points - it's a great question, ~Ray