5

I have a php page with information, and links to files, such as pdf files. The file types can be anything, as they can be uploaded by a user.

I would like to know how to force a download for any type of file, without forcing a download of links to other pages linked from the site. I know it's possible to do this with headers, but I don't want to break the rest of my site.

All the links to other pages are done via Javascript, and the actual link is to #, so maybe this would be OK?

Should I just set

header('Content-Disposition: attachment;)

for the entire page?

dimo414
  • 47,227
  • 18
  • 148
  • 244
Joshxtothe4
  • 4,061
  • 10
  • 53
  • 83

2 Answers2

14

You need to send these two header fields for the particular resources:

Content-Type: application/octet-stream
Content-Disposition: attachment

The Content-Disposition can additionally have a filename parameter.

You can do this either by using a PHP script that sends the files:

header('Content-Type: application/octet-stream');
header('Content-Disposition: attachment');
readfile($fileToSend);
exit;

And the filenames are passed to that script via URL. Or you use some web server features such as mod_rewrite to force the type:

RewriteEngine on
RewriteRule ^download/ - [L,T=application/octet-stream]
Gumbo
  • 643,351
  • 109
  • 780
  • 844
6

Slightly different style and ready to go :)

$file = 'folder/' . $name;

if (! file) {
    die('file not found'); //Or do something 
} else {
    // Set headers
    header("Cache-Control: public");
    header("Content-Description: File Transfer");
    header("Content-Disposition: attachment; filename=$file");
    header("Content-Type: application/zip");
    header("Content-Transfer-Encoding: binary");
    // Read the file from disk
    readfile($file); 
}
Mantichora
  • 385
  • 4
  • 8
  • What if I want the file to be saved automatically, without the user being prompted to save the file. – Geoffrey Apr 08 '11 at 13:35