问题
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