views:

37

answers:

3

Hi guys, I have a script which uploads files into an online directory and stores the file details in a database. The files when stored are renamed to the id of the entry in the database. Whenever a user requests a download, a simple SQL statement retrieves the file details from the database, the contents of the file are read from the database, and the file is prompted for download. The following is my code:

$one_file = $FILE_OBJECT->get($_GET['id']); // this is an object which just grabs the file details from the database


header("Content-type: ".$one_file['type']); // add here more headers for diff. extensions
header("Content-Disposition: attachment; filename=\"".$one_file["filename"]."\""); // use 'attachment' to force a download
header("Content-type: application/octet-stream");
header("Content-Disposition: filename=\"".$one_file["filename"]."\"");

readfile(_config('files_path').$_GET['id']);// reading the actual raw file stored in my online directory

Problem is that Im testing using a word document and its uploading perfectly - I've even checked the raw file being uploaded by manually changing its extension and it's uploading perfectly. The problem is that when it's downloaded using the code above, the Word file seems corrupted or something, because when I try to open it, it's all mumbled and jumbled. What's happening? I've used this snippet on a few other sites I've worked on, and they work perfectly fine... Help please!

+2  A: 

By default PHP's header function will replace previous headers with the same name, so your first two headers are being overwritten by the second two. Delete the second two and see if that works.

Ian Wetherbee
Did that but didn't help at all.. the problem is somewhere within the above mentioned code snippet as the file is being stored fine on the online directory.
Ali
It might be an encoding issue with readfile, try adding `header("Content-Transfer-Encoding: binary");` Do other filetypes work? Try uploading a plain text file.
Ian Wetherbee
+1  A: 

See if this helps:

http://stackoverflow.com/questions/3019068/webkit-and-excel-filephpexcel/3019179#3019179

Nathan Loding
Thanjs man - I still don't know exactly why my code stopped working all of a suddent...
Ali
A: 

I was having the same problem: every time I downloaded a file, it was supposedly "corrupt". Turns out I had made a stupid directory path mistake, but the php error was being written into the downloaded file. Which, of course, made it "corrupt".

Actually I solved by reading Ian Wetherbee's comment about testing with a plain text file. Thanks Ian!

JMC Creative