Downloaded word document not correct

Do you have a question? Post it now! No Registration Necessary.  Now with pictures!

Threaded View
Hi everyone,

I'm using PHP and a DB to control access to files that have been
uploaded by users. I am using the following PHP code snippet to
deliver the file after the access rights have been checked.

        $theFile = file_get_contents(UPLOAD_PATH.$storedName);
        if($mimeExtension == '')
            header("Content-Type: application/octet-stream\n");
            header("Content-Type: $mimeExtension\n");
        header("Content-Disposition: attachment; filename=
        // doesn't work with base64 or binary
        header("Content-Transfer-Encoding: binary\n");
        header("Content-length: " . strlen($theFile) . "\n");

        echo $theFile;

Now, text files open up fine. Word documents though, especially those
with embedded photos, come out mangled. I have tried sending the word
document with the content type being sent to both application/octet-
stream and the word document one. The file on the server (which is my
computer, as I am currently developing the site) is fine. This means
that something goes wrong while the file is being sent. I suspect the
Content-Transfer-Encoding header, but setting it to binary (which was
my original code) or base64 doesn't fix the problem. What could
possible be the problem?

Secondly, when the user presses 'save', the save button remains
depressed until the document has finished uploading. It's as if the
save operation 'blocks', rather than adding the save to the download
manager and getting rid of the save screen. That is, the 'save as'
screen remains visible, with the save button pressed down, until the
file is completely downloaded. How can I avoid this?



Re: Downloaded word document not correct

In case anyone runs into the same problem, the problem I was having
was caused because output buffering was turned on. Turning off output
buffering solved the problem.

Couple of questions though:

1) Why would only word documents get confused by this? I could
succesfully download PDFs with ob buffering turned on, for example.
2) I checked the buffer to see what was in it just before turning it
off. It had "\r\n\r\n" which, in HTTP, indicates that header data has
finished and what follows is actual data. Where did these characters
in the buffer come from?
3) Related to question 2. Even though the buffer had data in it prior
to sending headers, I could succesfully send headers. Usually if you
try to send headers after outputting data PHP throws an error.

Quoted text here. Click to load it

Site Timeline