Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

forcing a file to download [duplicate]

Tags:

php

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?

like image 397
Joshxtothe4 Avatar asked May 29 '09 13:05

Joshxtothe4


2 Answers

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]
like image 54
Gumbo Avatar answered Oct 08 '22 17:10

Gumbo


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); 
}
like image 35
Mantichora Avatar answered Oct 08 '22 15:10

Mantichora