How to Force the Download of a File with HTTP Headers and PHP

It’s quite a common scenario with the web to want to force a file to download, instead of allowing the browser to open it. This can apply to images, pdfs, html, anything a web browser can open (which is more and more these days).

To accomplish this, we need to set some http response headers:

Content-Type: application/octet-stream
Content-Disposition: attachment; filename="test.txt"

Within PHP was can do this with a function like:

function forceDownload($filename, $type = "application/octet-stream") {
    header('Content-Type: '.$type.'; charset=utf-8');
    header('Content-Disposition: attachment; filename="'.$filename.'"');
}

Which was can then use to download a file like this:

forceDownload("wiki.html", "text/html");
echo file_get_contents("http://www.wikipedia.org");

Alternative#

With the HMTL5 specification you can now add the download attribute to any a tag to force the download.

<a href="afile.txt" download="filename.txt">download</a>

Hope you found this useful – any questions let us know in the comments.