Headers to Send to Force a Download in PHP

It can be difficult sometimes to force a web browser to popup a dialog to let someone download a file. A lot of times with things like a pdf or Microsoft Office files (Word, Excel, etc), browsers like Internet Explorer will just open them with a sub program in the browser. This can be annoying for both the developer and user. However to be honest with you, I am not sure if this is as big of an issue as it was a few years ago (with the way browsers are changing to enhance security).

Anyway, if you want to force a browser to accept a file as a download instead of opening it, I have found it is best to just be as vague as you can in your headers so the browser wont know what to do with it besides ask the user. Below is what I have used for years and it always seems to work no matter what browser or computer you are on.

header('Content-Type: application/force-download');
header('Content-Disposition: attachment; filename="myfile.abc"');
header('Content-Length: ' . filesize('myfile.abc'));

readfile('myfile.abc');

This is something I just want to log for posterity out of an old email of mine.

Leave a Reply

{
}