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?
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]
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);
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With