Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP: send WORD document file to download

This question is trivial and has many answers, all the same or nearly but for my case, it doesn't solve as expected? Goal: send WORD file as attachment with PHP (simple...) Mean: here is the code:

// send the file to the browser
header("Cache-Control: no-store");
header("Content-Type: application/octet-stream");
//header("Content-type: application/msword");
header('Content-Disposition: attachment; filename="'. basename($filename) . '"');
header('Content-Transfer-Encoding: binary');
header('Content-Length: '. filesize($filename));
ob_clean();
flush();
readfile($filename);
exit();

Well, everything seems right but the file I saved on my computer cannot be read by MS-WORD: it reads some special chars like:

PK ! /Œt1« á [Content_Types].xml ...

But if I open the original from the server, everything is ok. I missed something obvious... Any advice is welcome because I tried nearly ALL the methods I read...but still the same result.

like image 754
Yoong Kim Avatar asked Jan 27 '26 08:01

Yoong Kim


1 Answers

Maybe your uotput file get wrong header. I have something like this in my script, which i use to download files:

$tmp = explode(".",$file['filename']);
switch ($tmp[count($tmp)-1]) {
  case "pdf": $ctype="application/pdf"; break;
  case "exe": $ctype="application/octet-stream"; break;
  case "zip": $ctype="application/zip"; break;
  case "docx":
  case "doc": $ctype="application/msword"; break;
  case "csv":
  case "xls":
  case "xlsx": $ctype="application/vnd.ms-excel"; break;
  case "ppt": $ctype="application/vnd.ms-powerpoint"; break;
  case "gif": $ctype="image/gif"; break;
  case "png": $ctype="image/png"; break;
  case "jpeg":
  case "jpg": $ctype="image/jpg"; break;
  case "tif":
  case "tiff": $ctype="image/tiff"; break;
  case "psd": $ctype="image/psd"; break;
  case "bmp": $ctype="image/bmp"; break;
  case "ico": $ctype="image/vnd.microsoft.icon"; break;
  default: $ctype="application/force-download";
}

header("Pragma: public"); // required
header("Expires: 0");
header("Cache-Control: must-revalidate, post-check=0, pre-check=0");
header("Cache-Control: private",false); // required for certain browsers
header("Content-Type: $ctype");
header("Content-Disposition: attachment; filename=\"".$filename."\";" );
header("Content-Transfer-Encoding: binary");
header("Content-Length: ".$fsize);
ob_clean();
flush();
readfile( 'files/'.$file['filename'] );

Filename I take from db.

like image 172
miszczu Avatar answered Jan 29 '26 20:01

miszczu