PHP Outputting File Attachments with Headers
Solution 1
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.
Solution 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]);
OneNerd
Updated on June 16, 2022Comments
-
OneNerd almost 2 years
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:
When its a text file, I am getting a strange symbol as the first letter in the text document
When its a word doc, it is corrupt (presumably that same first bit or byte throwing things off).
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.