I am having problems trying to execute a .docx file using php. When uploading a file, I determine the mime file type and upload the file using a file with the correct extension based on the mime type; for example below:
application/msword - doc
application/vnd.openxmlformats-officedocument.wordprocessingml.document - docx
When you try to serve files for download, I do the opposite in detecting extensions and services based on the mime type, for example.
public static function fileMimeType($extention) {
if(!is_null($extention)) {
switch($extention) {
case 'txt':
return 'text/plain';
break;
case 'odt':
return 'application/vnd.oasis.opendocument.text';
break;
case 'doc':
return 'application/msword';
break;
case 'docx':
return 'application/vnd.openxmlformats-officedocument.wordprocessingml.document';
break;
case 'jpg':
return 'image/jpeg';
break;
case 'png':
return 'image/png';
break;
case 'pdf':
return 'application/pdf';
break;
default:
break;
}
}
}
All files load correctly and open normally, but when you try to open a docx file, Word (in several files) generates an error indicating that the file is damaged.
Any ideas would be great, thanks.
Edit # 1
try {
$file = new Booking_Document((int)$get_data['bookingDocument']);
header('Content-Type: ' . Booking_Document::fileMimeType($file->getDocumentType()));
header('Content-Disposition: attachment; filename=' . $file);
header('Expires: 0');
header('Cache-Control: must-revalidate, post-check=0, pre-check=0');
header('Pragma: public');
echo readfile(Zend_Registry::get(static::$_uploadDir).$this->_id);
} catch (Exception $e) {
View_Helpers_FlashMessages::addMessage(array('message' => $e->getMessage(), 'type' => 'error'));
}
exit;
Fixed
Before calling readfile (), I added ob_clean () and flush (), which seemed to fix the problem.
user275074