1

I have a function which I use to enable downloading of files from a non-public directory. The downloading part works fine except that it does not prompt the user before and allowing the user to choose the location or just a simple open.

I use the following code:

$file = L_APP_BILAGOR."/".$_GET["f"];
$finfo = new finfo(FILEINFO_MIME);
$ct = $finfo->file($fileName);

if (file_exists($file)) {
   header('Content-Type: '.$ct);
   header('Content-Disposition: attachment; filename='.basename($file));
   header('Content-Transfer-Encoding: binary');
   header('Expires: 0');
   header('Cache-Control: must-revalidate, post-check=0, pre-check=0');
   header('Pragma: public');
   header('Content-Length: ' . filesize($file));
   ob_clean();
   flush();
   readfile($file);
   exit;
}

Can't seem to get it right. How do I force the browser to prompt the user before downloading the file?

2 Answers2

1

i am not sure if this is really a php thing, i believe it´s more based on the browser settings. in general your code looks okay for me, when i compare it with other examples.

michabbb
  • 880
  • 2
  • 7
  • 27
0

To stop Automatic downloads in chrome goto content setting which is chrome://settings/content

enter image description here

Then scroll to the bottom and your see the Automatic Downloads bit, then select your preference.

P.S Not really a question suited for Stackoverflow.

Lawrence Cherone
  • 46,049
  • 7
  • 62
  • 106
  • This does not seem to be the problem. I have tried with different browsers, all with automatic downloads disabled but the file is still downloaded directly when I click on the download link. @LozCherone – Christian Strid May 04 '14 at 09:56
  • ok np, very odd, looking at your code there is nothing wrong with it apart from it couldn't handle downloads over 2GB or beyond your memory limit, but it should already be prompting you to download so it **must be a browser settings issue** or something more shady/serious going on with your browser/s.. o_O – Lawrence Cherone May 04 '14 at 11:03
  • **Sidenote:** Also you should use `basename($_GET["f"])` or its possible to download **ANY** file including system/config files from your server! Someone may of already got in and replaced a file with something malicious then you have downloaded, run it. – Lawrence Cherone May 04 '14 at 11:14
  • I have changed `f` to an id instead of the filename which I use to fetch the filename from my DB. So the filename is not passed with GET anymore. I'm also thinking that maybe I should hash `f` and hide the actual id and use the hash as key instead. – Christian Strid May 04 '14 at 11:27