Home > PHP > Simple Function To Force Download Of A File

Simple Function To Force Download Of A File

The following function will allow you to run a file download through PHP, you could use this to help with tracking of downloads on a site for example. Or to force a Powerpoint file to download rather than open in the browser, no matter what the users browser settings.

Note however that if you are doing file integrity checksums (md5, sha1, etc.) against the file the file passed through in this way will not have the same checksum as the file when saved on the client machine or the file stored on the server.

  1.  
  2. //-----------------------------------------------
  3. // Function to force download of a file
  4. //-----------------------------------------------
  5. public function download($file_name, $file_path, $mime_type)
  6. {
  7.         header('Content-Description: File Transfer');
  8.         header('Content-Type: '.$mime_type);
  9.         header('Content-Disposition: attachment; filename="'.$file_name.'";');
  10.         header("Cache-Control: must-revalidate, post-check=0, pre-check=0");
  11.         header('Content-Length: ' .    filesize($file_path));
  12.         @readfile($file_path);
  13.         die();
  14. }

 

Related posts on coderchris.com:

  1. PHP5 Universal File Download Class
    After finding different hosting companies having wildly different policies when it comes to what's enabled...
  2. ctype_digit rtfm!
    For the last 5-10 minutes I've been wondering why a check on a variable which...
  3. Dodgy Wordpress Plugins and Themes
    Recently I have been doing a LOT of research into various wordpress themes and plugins...
  4. File-system mp3 Organisation – Is It Really That Hard?
    Like most people I know I have a lot of mp3's and every person likes...
  5. Why @ is NOT your friend
    Ah, the error suppression operator (@) It seems like such a fantastic idea, just put...

Categories: PHP Tags:
  1. No comments yet.
  1. No trackbacks yet.