Tag Archive for 'snippet'

Force a file download

Here's a small function that will allow you to force a file download.

PHP:
  1. /**
  2. * Force a file download via HTTP.
  3. *
  4. * File is required to be on the same server and accessible via a path.
  5. * If the file cannot be found or some other error occurs then a
  6. * '204 No content' header is sent.
  7. *
  8. * @param string $path Path and file name
  9. * @param string $name Name of file when saved on user's computer,
  10. *                     null for basename from path
  11. * @param string $type Content type header info (e.g., 'application/vnd.ms-excel')
  12. * @return void
  13. * @access public
  14. */
  15. /* public static */ function download($path, $name = null, $type = 'binary/octet-stream')
  16. {
  17.     if (headers_sent()) {
  18.         echo 'File download failure: HTTP headers have already been sent and cannot be changed.';
  19.         exit;
  20.     }
  21.    
  22.     $path = realpath($path);
  23.     if ($path === false || !is_file($path) || !is_readable($path)) {
  24.         header('HTTP/1.0 204 No Content');
  25.         exit;
  26.     }
  27.  
  28.     $name = (empty($name)) ? basename($path) : $name;
  29.     $size = filesize($path);
  30.  
  31.     header('Expires: Mon, 20 May 1974 23:58:00 GMT');
  32.     header('Last-Modified: ' . gmdate('D, d M Y H:i:s') . ' GMT');
  33.     header('Cache-Control: no-store, no-cache, must-revalidate');
  34.     header('Cache-Control: post-check=0, pre-check=0', false);
  35.     header('Cache-Control: private');
  36.     header('Pragma: no-cache');
  37.     header("Content-Transfer-Encoding: binary");
  38.     header("Content-type: {$type}");
  39.     header("Content-length: {$size}");
  40.     header("Content-disposition: attachment; filename=\"{$name}\"");
  41.     readfile($path);
  42.     exit;
  43. }

Very easy to use, too! Here are some examples of how you might call the function:

PHP:
  1. download('./myfile.txt');
  2.  
  3. download(__FILE__, 'a file for you.php');
  4.  
  5. download('/home/you/files/spreadsheet.xml', 'ssheet_' . date('Ymd'), 'application/vnd.ms-excel');