输出缓冲的php文件下载 [英] output buffering for php file download

查看:107
本文介绍了输出缓冲的php文件下载的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我可以这样做吗?

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();

目前我正在下载正确命名的文件,但该文件的内容是html输出来自包含上述代码的php。

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.

我已验证$ path是正确的。一个糟糕的$ size会导致这种情况发生吗?
我也在ob_start()之后直接尝试ob_flush()。

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().

编辑:当前代码:

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");

以上代码会导致同样的问题。文件下载,命名正确,显然存在并且大小正确,但文件内容是页面的html输出。

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.

提前致谢

我刚刚注意到这是在文件的最后下载(错误):
int(14)content

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.

推荐答案

也许一些调试可能有所帮助:

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");

这篇关于输出缓冲的php文件下载的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆