views:

58

answers:

5

If you have images or other files that reside externally, how do force the browser to download the link when a user click on it?

The use of "Content-disposition: attachment;" header would do that, but it is not working for files that resides externally without reading and importing the file locally.

+1  A: 

This is not possible. You cannot dictate a client how to handle a different resource than the currently requested one.

You could only use a proxy to fetch the external external file and pass it to the client.

Gumbo
A: 

I don't think it is possible to force a file download if you are not controlling the HTTP headers. Content-disposition: attachment is the only way I know of to accomplish this.

Though this is probably not going to work, my only guess would be trying to combine Content-disposition with a Location header:

Content-disposition: attachment; filename=myfile.jpg
Location: http://www.somesite.com/myfile.jpg

(it's a long shot, probably invalid and/or just bad practice)

pix0r
A: 

You can try this by writing in .htaccess file code like this:

<Files *.xls>
  ForceType application/octet-stream
  Header set Content-Disposition attachment
</Files>
<Files *.eps>
  ForceType application/octet-stream
  Header set Content-Disposition attachment
</Files>
antyrat
This isn't going to work. The `.htaccess` needs to be placed in the same folder as the actual file.
BalusC
+1  A: 

You will have to load the resource on the server first. You might want to do some caching also:

<?php
  header("Content-disposition: attachment; filename=myfile.jpg");
  echo file_get_contents("http://host.tld/path/to/myfile.jpg");
?>
Byron Whitlock
But file_get_contents() will read the file to the local server which is what I try to avoid.
Cory
Only temporarily in memory or temp disk. It's however your best bet. There are really no other ways. You *have* to act as proxy whenever you'd like to change the response headers of an external resource.
BalusC
A: 

I use a combination of the aforementioned "Content-Disposition" header, as well as forcing the type:

header("Content-type: attachment/octet-stream");
header('Content-disposition: attachment; filename="'.$filename.'"');
Pickle