title: PHP Outputting File Attachments with Headers
body: <p>After reading a few posts here I formulated this function which is sort of a mishmash of a bunch of others:</p>
  
  <pre><code>function outputFile( $filePath, $fileName, $mimeType = '' ) {
      // Setup
      $mimeTypes = array(
          'pdf' =&gt; 'application/pdf',
          'txt' =&gt; 'text/plain',
          'html' =&gt; 'text/html',
          'exe' =&gt; 'application/octet-stream',
          'zip' =&gt; 'application/zip',
          'doc' =&gt; 'application/msword',
          'xls' =&gt; 'application/vnd.ms-excel',
          'ppt' =&gt; 'application/vnd.ms-powerpoint',
          'gif' =&gt; 'image/gif',
          'png' =&gt; 'image/png',
          'jpeg' =&gt; 'image/jpg',
          'jpg' =&gt; 'image/jpg',
          'php' =&gt; 'text/plain'
      );
  
      // Send Headers
      //-- next line fixed as per suggestion --
      header('Content-Type: ' . $mimeTypes[$mimeType]); 
      header('Content-Disposition: attachment; filename="' . $fileName . '"');
      header('Content-Transfer-Encoding: binary');
      header('Accept-Ranges: bytes');
      header('Cache-Control: private');
      header('Pragma: private');
      header('Expires: Mon, 26 Jul 1997 05:00:00 GMT');
      readfile($filePath);
  
  }
  </code></pre>
  
  <p>I have a php page (file.php) which does something like this (lots of other code stripped out):</p>
  
  <pre><code>   // I run this thru a safe function not shown here
  $safe_filename = $_GET['filename']; 
  outputFile ( "/the/file/path/{$safe_filename}", 
               $safe_filename, 
               substr($safe_filename, -3) );
  </code></pre>
  
  <p>Seems like it should work, and it almost does, but I am having the following issues:</p>
  
  <ol>
  <li><p>When its a text file, I am getting a strange symbol as the first letter in the text document</p></li>
  <li><p>When its a word doc, it is corrupt (presumably that same first bit or byte throwing things off).</p></li>
  <li><p>I presume all other file types will be corrupt - have not even tried them</p></li>
  </ol>
  
  <p>Any ideas on what I am doing wrong?</p>
  
  <p>Thanks -</p>
  
  <p><strong>UPDATE:</strong> changed line of code as suggested - still same issue.</p>