2
header("Pragma: public");
header("Expires: 0");
header("Cache-Control: must-revalidate, post-check=0, pre-check=0");
header("Cache-Control: private",false);
header("Content-type: application/force-download");
header("Content-Disposition: attachment; filename=\"". $file ."\";");
header("Content-Transfer-Encoding: binary");
header("Content-Length: ".filesize($file));
file_get_contents($file);
readfile($file);
exit();

Any idea what I'm doing wrong? Shouldn't this download any file from my server to the harddrive of the user? Somehow every file is damaged! Moreover I wonder how I can change the filename of the downloaded file?

$file always contains the full path to my file. if I try header('Location:' . $file ); the browser successfully opens my file. however if the file is a .jpg the browser doesn't prompt the download window. instead it just opens the file in the browserwindow. I want every file to be downloaded to the hd.

Please help me guys. I'm after this for over a week now and I can't find a solution?

slava
  • 1,901
  • 6
  • 28
  • 32
matt
  • 42,713
  • 103
  • 264
  • 397
  • If $file contains a path and not only the name you should use `filename=\"". basename($file) ."\";"` and what is the `file_get_contents($file);` line supposed to do? – VolkerK Jul 23 '10 at 00:54

1 Answers1

4

Why not use

header("Content-type: application/octet-stream");

Instead of "force-download"

Also why are you doing file_get_contents and readfile? Only one is needed - You are basically including the file twice which is why it's corrupted. Here is how I would execute the above code:

header("Cache-Control: no-cache");
header("Expires: -1");
header("Content-Type: application/octet-stream;");
header("Content-Disposition: attachment; filename=\"" . basename($file) . "\";");
header("Content-Transfer-Encoding: binary");
header("Content-Length: " . filesize($file));
echo file_get_contents($file);

That should be sufficient - so long as the file actually exists

Marco Ceppi
  • 7,163
  • 5
  • 31
  • 43
  • 2
    I'd prefer `readfile($file)` over `echo file_get_contents($file)`. No need to read the entire file content into memory (as a string) and then echo it. – VolkerK Jul 23 '10 at 01:01
  • This is very true. The main issues with the script was the lack of basename for content-disposition and the inclusion of two "file reading" functions. `readfile` would probably be more suited - I've just always used `file_get_contents` – Marco Ceppi Jul 23 '10 at 01:07