PHP 在服务器上将文件回显为文本而不是二进制文件

PHP echos file as text instead of binary on server

我写了一个 PHP 页面,它读取一个文件并在添加一些 headers:

后回显它
header('Content-disposition: filename="' . $fname . '"');
header('Pragma: no-cache');
header('Expires: 0');
header('Cache-Control: must-revalidate, post-check=0, pre-check=0');
header('Pragma: public');
header("Content-type: $AttachFileType");
header("Content-Transfer-Encoding: binary");
header("Content-Length: " . filesize($ffullname));
echo file_get_contents($ffullname);

这段代码在本地测试还不错,但是移植到服务端时,响应却不尽如人意。例如,当我想检索一个 png 文件时,我在本地测试中得到以下图像:

而服务器测试输出这个:

据我调查,它们之间的唯一区别是服务器响应增加了 4 个 headers。本地测试响应 headers:

Cache-Control: must-revalidate, post-check=0, pre-check=0
Connection: Keep-Alive
Content-disposition: filename="attachment_hrmstotal_generalskills_6.png"
Content-Length: 2401
Content-Transfer-Encoding: binary
Content-Type: png
Date: Wed, 23 May 2018 04:45:02 GMT
Expires: 0
Keep-Alive: timeout=5, max=97
Pragma: public
Server: Apache/2.4.27 (Ubuntu)

和服务器响应headers是这些:

Cache-Control: must-revalidate, post-check=0, pre-check=0
Connection: keep-alive
Content-disposition: filename="attachment_hrmstotal_generalskills_1.png"
Content-Length: 184450
Content-Transfer-Encoding: binary
Content-Type: png
Date: Wed, 23 May 2018 04:40:56 GMT
Expires: 0
Pragma: public
Server: nginx/1.8.0
Strict-Transport-Security: max-age=31536000
X-Content-Type-Options: nosniff
X-Frame-Options: SAMEORIGIN
X-XSS-Protection: 1; mode=block

后四位headers就是区别。问题是什么,原因以及解决方法?

您的内容类型应该是 Content-type: image/png