Home » Php » download – Sending a .docx file to the Browser with PHP

download – Sending a .docx file to the Browser with PHP

Posted by: admin February 25, 2020 Leave a comment

Questions:

I am struggling to send a Word .docx file to the browser. The Word file opens fine, if I create a link to the Word file, it also opens fine.

However when using this code:

            // output the file to the browser
            if ($fileToOutput) {
                header("Content-Description: File Transfer");
                header('Content-Type: application/vnd.openxmlformats-officedocument.wordprocessingml.document');
                header('Cache-Control: must-revalidate, post-check=0, pre-check=0');
                header('Expires: 0');
                header('Pragma: public');
                //header('Content-Length: ' . filesize($fileToOutput)); // this is causing the file download to fail

                header('Content-Type: application/octet-stream');
                header("Content-Transfer-Encoding: Binary");
                header("Content-disposition: attachment; filename=\"" . basename($fileToOutput) . "\"");
                ob_clean();
                flush();
                readfile($fileToOutput);
                exit;
            }

I get the following:

Word found unreadable content

Followed by the dreaded “Word experienced an error trying to open the file.”:

Word experienced an error trying to open the file

Like I said, the Word file opens fine, and downlaods from a link fine – I only get these errors when trying to output the Word file with the above PHP code.

Where is this PHP code going wrong?

How to&Answers: