Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP Outputting File Attachments with Headers

Tags:

file

php

header

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.

like image 952
OneNerd Avatar asked May 22 '09 02:05

OneNerd


1 Answers

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.

like image 119
OneNerd Avatar answered Sep 23 '22 02:09

OneNerd