PHP Header Force Download Of Files


In apache, the file type will usually determine how the file is handled. It can opened and displayed in the browser or download, etc. For example, images, css, javascript, php, html (and other types) files are executed and displayed within the browser whereas PDF, ZIP, EXE and other unknown file types will be downloaded by the browser. Usually this behaviour is suitable however we may want to change how certain file types are handled and then force an Image or PHP script file to be downloaded.

PHP Header Force Download Of Files

The below PHP Header code will force any file to be downloaded rather than just being displayed in a browser. You can use this code to force PDF download or to force an Image to download or force download of a javascript file rather than having these file types displayed or executed by the browser.

PHP Header Code To Force File Download


/* The name of the file we want to force a download */
$filename = 'somefile.html';

/* set our content type to match the file we are downloading */
header("Content-Type: text/html");
/* Tell the browser how big the file is going to be */
header("Content-Length: ".filesize($filename)."\n\n");
/* force the file to be downloaded */
header("Content-Disposition: attachment; filename=$filename");

/* echo out the contents of the file */
echo file_get_contents($filename);

Important Note

Remember that since we are sending headers, we need to make sure that there is no output sent to the browser before the headers are sent. Also, the file mime type should match the file type, such as a mime-type of image/png for PNG files and application/pdf to force a PDF file to download.

Note that you can force the download to have a different name by changing the filename for the Content-Disposition header to the filename of your choice.
For a more complete list of file mime-types, you should visit my article on list of file mime-types. If you would like to learn to to determine the mime-type based on the file extensions, check out this article.