php header('Content-type: application/octet-stream') 导致 0 字节文件

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/11175933/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-24 23:55:14  来源:igfitidea点击:

header('Content-type: application/octet-stream') cause 0 byte files

phpdownload

提问by Akos

I'm using database query in PHP to retrieve a binary file. But when I'm trying to force download it, the header('Content-type: application/octet-stream') line cause 0 byte files. Without that line I can download the file with full content. It's a binary file that's for sure so I just can't understand why that line causes the problem. The code:

我在 PHP 中使用数据库查询来检索二进制文件。但是当我试图强制下载它时, header('Content-type: application/octet-stream') 行会导致 0 字节文件。如果没有该行,我可以下载包含完整内容的文件。这是一个可以肯定的二进制文件,所以我无法理解为什么该行会导致问题。编码:

$result = mysql_query("SELECT data FROM stored_file WHERE file_name = '$q'");

while($row = mysql_fetch_array($result))
{
    $file = $row['data'];
}


    header('Content-disposition: attachment; filename='.$q);
    header('Content-type: application/octet-stream');
    header('Content-Length: '.filesize($file));
    header("Pragma: no-cache");
    header("Expires: 0");
    echo $file;

Any idea? Thanks.

任何的想法?谢谢。

采纳答案by mario

filesize()won't return a meaningful value.

filesize()不会返回有意义的值。

You have binary data in $file, notan actual filenameas required as first parameter. Hence you would get an error. (Enable error_reporting! Not seeing errors, and not having them are two different things.)

您在 中有二进制数据$file而不是第一个参数所要求的实际文件名。因此你会得到一个错误。(启用 error_reporting!没有看到错误和没有它们是两件不同的事情。)

So what you want to use there is strlen($file), not filesize().

所以你想在那里使用的是strlen($file),而不是filesize()

Btw, application/octet-streamor other fill-ins have no use for forcing downloads. It's the Content-Disposition:header which is most crucial to that effect. You're still allowed to send the correct MIME type.

顺便说一句,application/octet-stream或其他填充没有用于强制下载。这Content-Disposition:是对这种效果最关键的标题。您仍然可以发送正确的 MIME 类型。

回答by user2894190

From looking at the query I guess that in $row['data']is the binary data stored. To set the correct Content-Length header you should use mb_strlen($row['data']);. If no multibyte support (the mb_ functions) is activated on your machine, use strlen(). But be aware, this may result in akward results because the binary data could actually contain the EOF byte sequence and return a too short length. With the mb_strlen function you are on the save side.

从查看查询我猜, in$row['data']是存储的二进制数据。要设置正确的 Content-Length 标头,您应该使用mb_strlen($row['data']);. 如果您的机器上没有激活多字节支持(mb_ 函数),请使用 strlen()。但请注意,这可能会导致错误的结果,因为二进制数据实际上可能包含 EOF 字节序列并返回太短的长度。使用 mb_strlen 函数,您就处于保存状态。