Problems generating word documents on server side for security reasons

Posted on 16th Feb 2014 by admin

I have a problem with word documentation generation when generating a word document (docx) with PHP. I am doing this for security reasons, as I do not want people to be able to directly access a file with urls, so I store the files above the web root and they are generated on the server side on demand. Here is my code for manually testing file generation of a .docx file ( a Word 2007 file ):

$path = "../../uploads_productionization/file_for_category_1_tab_2/adsfdafds.docx

// We'll be outputting a docx
header( 'Content-type: application/vnd.openxmlformats & -officedocument.wordprocessingml.document.main+xml');

// It will be called downloaded.docx
header('Content-Disposition: attachment; filename="downloaded.docx"');

// The word source is in adsfdafds.docx
readfile($path);


When I execute this code, ie when I manually generate a docx file, I get two error messages:

"The Open Office XML document cannot be opened because there are problems with the contents"
Details: "File is corrupt and cannot be opened"

Next message:
"Word found unreadable content in downloaded.docx. Do you want to recover the contents of this document? If so, please click Yes"

When I click Yes on the second message, the document opens. Sometimes the file is okay, sometimes it isn't when there are pictures and formatting and so on and so forth.

Anyone have a solution for this problem? Been trying to get around this for at least a week...

P.S. All other files, PDFs, text files, work fine.. I think it's just office documents.

Other forums