PHP Output file attachments with headers

After reading a few posts here, I formulated this function, which is a kind of Mishmar from several groups:

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) that does something like this (many other divided sections):

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

It seems like it should work, and it is almost so, but I am having the following problems:

  • When its a text file, I get a weird character as the first letter in a text document

  • When this word is doc, it is corrupted (presumably the same first bit or byte throws things away).

  • I assume that all other types of files will get corrupted - did not even try them

Any ideas on what I'm doing wrong?

Thanks -

UPDATE: changing the line of code as suggested is another problem.

+3
2

, .

script .

, include_once, , .

+3

, , ,

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

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

Source: https://habr.com/ru/post/1708865/


All Articles