views:

3757

answers:

3

What code do you need to add in PHP to automatically have the browser download a file to the local machine when a link is visited?

I am specifically thinking of functionality similar to that of download sites that prompt the user to save a file to disk once you click on the name of the software?

+9  A: 

Here is an example of sending back a pdf.

header('Content-type: application/pdf');
header('Content-Disposition: attachment; filename="' . basename($filename) . '"');
header('Content-Transfer-Encoding: binary');
readfile($filename);

@Swish I didn't find application/force-download content type to do anything different (tested in IE and Firefox). Is there a reason for not sending back the actual MIME type?

Also in the PHP manual Hayley Watson posted:

If you wish to force a file to be downloaded and saved, instead of being rendered, remember that there is no such MIME type as "application/force-download". The correct type to use in this situation is "application/octet-stream", and using anything else is merely relying on the fact that clients are supposed to ignore unrecognised MIME types and use "application/octet-stream" instead (reference: Sections 4.1.4 and 4.5.1 of RFC 2046).

Also according IANA there is no registered application/force-download type.

grom
+7  A: 

Send the following headers before outputting the file:

header("Content-Disposition: attachment; filename=\"" . basename($File) . "\"");
header("Content-Type: application/force-download");
header("Content-Length: " . filesize($File));
header("Connection: close");

@grom: Interesting about the 'application/octet-stream' MIME type. I wasn't aware of that, have always just used 'application/force-download' :)

Swish
A: 

Thank you sir! just 2 lines are more then sufficient

header("Content-Type: application/octet-stream"); header('Content-Disposition: attachment; filename="' . basename(filename) . '"');

It is working in my website www.4freemusicdownload.com