PHP Outputting File Attachments with Headers

Posted by OneNerd on Stack Overflow See other posts from Stack Overflow or by OneNerd
Published on 2009-05-22T02:45:02Z Indexed on 2010/05/19 7:40 UTC
Read the original article Hit count: 233

Filed under:
|
|

After reading a few posts here I formulated this function which is sort of a mishmash of a bunch of others:

function outputFile( $filePath, $fileName, $mimeType = '' ) {
    // Setup
    $mimeTypes = array(
        'pdf' => 'application/pdf',
        'txt' => 'text/plain',
        'html' => 'text/html',
        'exe' => 'application/octet-stream',
        'zip' => 'application/zip',
        'doc' => 'application/msword',
        'xls' => 'application/vnd.ms-excel',
        'ppt' => 'application/vnd.ms-powerpoint',
        'gif' => 'image/gif',
        'png' => 'image/png',
        'jpeg' => 'image/jpg',
        'jpg' => 'image/jpg',
        'php' => '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);

}

I have a php page (file.php) which does something like this (lots of other code stripped out):

   // 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) );

Seems like it should work, and it almost does, but I am having the following issues:

  1. When its a text file, I am getting a strange symbol as the first letter in the text document

  2. When its a word doc, it is corrupt (presumably that same first bit or byte throwing things off).

  3. I presume all other file types will be corrupt - have not even tried them

Any ideas on what I am doing wrong?

Thanks -

UPDATE: changed line of code as suggested - still same issue.

© Stack Overflow or respective owner

Related posts about php

Related posts about files