A simple function that we need every once in awhile is to download a file. The problem sometimes is that there are numerous amounts of browser plugins that will open the file within the browser itself instead of opening the browsers download manager and downloading the file to the hard disk such as microsoft IE’s office plugin that will display an excel spreadsheet or word document in the browser itself. Here’s a simple function that will send http headers to your browser and tell it to download the file instead of running in the browser.
The Code
function download_as_file($file, $type = '', $name = '') { if ($type != '') { if ($name != '') { header("Content-Disposition: attachment; filename=" . urlencode($name . '.' . $type)); } else { $file_name = explode('.', $file); header("Content-Disposition: attachment; filename=" . urlencode($file_name[0] . '.' . $type)); } } else { header("Content-Disposition: attachment; filename=" . urlencode($file)); } header("Content-Type: application/force-download"); header("Content-Type: application/octet-stream"); header("Content-Type: application/download"); header("Content-Description: File Transfer"); header("Content-Length: " . filesize($file)); flush(); $fp = fopen($file, "r"); while (!feof($fp)) { echo fread($fp, 65536); flush(); } fclose($fp); }
This function reads the contents of a file and sends the headers to your browser to force it to download it as a file instead of displaying it in the browser.
