PHP Header Force Download Of Files
PHP Header Code To Force File Download
<?php /* 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);
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.