output buffering for php file download

孤街醉人 提交于 2019-12-24 20:25:12

问题


Can I do something like this?

ob_start();
header("Content-Type: application/msword");
header("Content-Disposition: attachment; filename=".$title);
header("Content-Length: ".$size);
header("Content-Transfer-Encoding: binary");
readfile($path);
ob_end_flush();

Currently I am getting the correctly named file to download, but the contents of the file is the html output from the php that contains the above code.

I have verified the $path to be correct. Would a bad $size cause this to happen? I have also tried to ob_flush() directly after ob_start().

EDIT: Current Code Below:

if (file_exists($path)){
    ob_start();
    header("Content-Type: application/msword");
    header("Content-Disposition: attachment; filename=".$title);
    header("Content-Length: ".filesize($path));
    header("Content-Transfer-Encoding: binary");
    readfile($path);
    ob_end_flush();
    die();
    } else die ("Not Found");

Above code results in the same problem. File is downloaded, named correctly, apparently exists and with correct size, yet contents of the file is the html output of the page.

Thanks in advance

I just noticed that this is at the very end of the file that downloads (incorrectly): "int (14) content"

But I am not knowingly outputting this anywhere in my code.


回答1:


Maybe some debugging may help:

if (file_exists($path)) {
  ob_start();
  header("Content-Type: application/msword");
  header("Content-Disposition: attachment; filename=".$title);
  header("Content-Length: ".filesize($path));
  header("Content-Transfer-Encoding: binary");
  readfile($path);
  ob_end_flush();
  die(); // To not send the HTML afterwards
} else die("Not found");


来源:https://stackoverflow.com/questions/13150692/output-buffering-for-php-file-download

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!