5

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.

1
  • Remove Accept-Ranges . Because it needs more code... Commented Jan 4, 2015 at 10:25

2 Answers 2

5

Ok, I figured it out.

The script above DOES work.

What was happening is I had a series of include_once files, and one of them had a blank line causing the issue.

Sign up to request clarification or add additional context in comments.

1 Comment

Be careful of the closing '?>' tag too. It's best to omit the closing tag as it can cause blank lines to be included too.
2

Not sure if this is the real answer, but I think you intended

header('Content-Type: ' . $mimeType);

to be

header('Content-Type: ' . $mimeTypes[$mimeType]);

1 Comment

thanks corey -- changed the line (which was certainly a but). Unfortunately, still same issue.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.