I am trying to open files with this function. For files *.pdf
and *.txt
it works fine, but if the file is *.doc
or *.odt
when downloading and opening it, strange characters appear.
$filepath = '/var/download/prueba.doc';
if(file_exists($filepath)) {
header('Content-Description: File Transfer');
header('Content-Type: application/octet-stream');
header('Content-Disposition: attachment; filename="'.basename($filepath).'"');
header('Expires: 0');
header('Cache-Control: must-revalidate');
header('Pragma: public');
header('Content-Length:'.filesize($filepath));
flush(); // Flush system output buffer
readfile($filepath);
exit();
}
What am I doing wrong? Is there any way to be able to open any type of file once downloaded? I don't need to open them online, I need to be able to download them and once downloaded, be able to read them on my PC.
Your code seems correct, so the problem you are experiencing could be due to two reasons:
<?php
.In pdf and txt documents there is no problem if there is something at the beginning, but the documents doc, docx, odt, etc (the last two are actually a compressed zip file) do not allow any addition, opening as text once the application is loaded , showing its raw content.
I recommend that you check both to solve your problem.
To be able to open a document like word or excel online you must have a library, here it explains how it would be to read an excel with php:
http://www.cristalab.com/tutoriales/open-and-read-archivos-excel-con-php-c38945l/
I hope it helps you in something.
As he mentioned in the comment you would have to use a viewer to see the documents, in the following example you can use the google one:
I hope I have been able to serve you or at least give you a guide.