PHP forcibly loads the .xlsx file

I am working on a site that allows teachers to upload documents, and students upload them. However, there is a problem. Microsoft Word files (.docx) load fine, but when loading the excel (xlsx) file, excel gives the dialog "This file is damaged and cannot be opened." Any help with this would be greatly appreciated!

My download code is as follows:

case 'xlsx': header('Content-type: application/vnd.openxmlformats-officedocument.spreadsheetml.sheet'); header('Content-Disposition: attachment; filename="' . $filename . '"'); header('Content-Transfer-Encoding: binary'); header('Expires: 0'); header('Pragma: no-cache'); readfile('./uploads/resources/courses/' . $filename); break; 
+4
source share
5 answers

this works fine on my local xampp setup, regardless of the extension, so from my point of view, no case argument is required unless I miss something.

I tested with docx, accdb, xlsx, mp3, nothing ...

 $filename = "equiv1.xlsx"; header('Content-type: application/octet-stream'); header('Content-Disposition: attachment; filename="' . $filename . '"'); header('Content-Transfer-Encoding: binary'); header('Expires: 0'); header('Pragma: no-cache'); 
+2
source

I have this problem and had a specification .

How to notice him

unzip . Checking the output file with unzip, I saw a warning in the second line.

 $ unzip -l file.xlsx Archive: file.xlsx warning file: 3 extra bytes at beginning or within zipfile ... 

xxd (hex viewer) : I saw the first 5 bytes with the following command

 head -c5 file.xlsx | xxd -g 1 0000000: ef bb bf 50 4b PK... 

Note the first 3 bytes of ef bb bf , which is BOM!

Why?

Maybe a php file with BOM or previous output from the library.

You must find where the file or command with the specification is located. In my case and right now I don’t have time to find it, but I solve it with the help of the output buffer.

 <?php ob_start(); // ... code, includes, etc ob_get_clean(); // headers ... readfile($file); 
+2
source

try the following:

 header("Content-Disposition: attachment; filename=\"$filename\""); header("Content-Type: application/vnd.ms-excel"); 
0
source

to try:

 <? //disable gzip @apache_setenv('no-gzip', 1); //set download attachment header('Content-Disposition: attachment;filename="filename.xlsx"'); //clean the output buffer ob_clean(); //output file readfile('filepath/filename.xlsx'); //discard any extra characters after this line exit; ?> 
0
source

Try adding an extra title.

 header('Content-Length: ' . filesize('./uploads/resources/courses/' . $filename)); 
0
source

All Articles