pdf文件显示为text / html而不是application / pdf

时间:2017-04-03 21:36:09

标签: php pdf http-headers content-type

我正在尝试在php应用程序中显示.pdf文件。它在我的本地开发设置中运行良好,但在生产时,相同的代码将pdf显示为乱码文本。

这些是我正在使用的请求标头:

<?php
$file = $_GET["f"];
$filename = 'contrato.pdf';
header('Content-type: application/pdf');
header('Content-Disposition: inline; filename="' .$filename. '"');
header('Content-Transfer-Encoding: binary');
header('Accept-Ranges: bytes');
readfile($file);
?>

这些是根据chrome的生产响应标题:

Connection:Keep-Alive
Content-Encoding:gzip
Content-Type:text/html
Date:Mon, 03 Apr 2017 21:31:19 GMT
Keep-Alive:timeout=15, max=189
Server:Apache
Transfer-Encoding:chunked
Vary:Accept-Encoding

在开发设置中,响应标头是:

Accept-Ranges:bytes
Connection:Keep-Alive
Content-Disposition:inline; filename="contrato.pdf"
Content-Transfer-Encoding:binary
Content-Type:application/pdf
Date:Mon, 03 Apr 2017 21:33:44 GMT
Keep-Alive:timeout=5, max=100
Server:Apache/2.4.7 (Win32) PHP/5.5.8
Transfer-Encoding:chunked
X-Powered-By:PHP/5.5.8

可能是由于apache设置?

1 个答案:

答案 0 :(得分:-2)

我认为这是错误:

header('Content-type: application/pdf');

请注意小写字母 t

这一行应该是这样的:

header('Content-Type: application/pdf');

另请注意,您正在使用$ _GET [&#34; f&#34;]阅读文件 这是错误的,而是从$ filename变量中读取文件。 将最后一行更改为:

readfile($filename);

无论如何,这里更正了你的代码:

<?php
$file = $_GET["f"];
$filename = 'abc.pdf';
header('Content-Type: application/pdf');
header('Content-Disposition: inline; filename="' .$file. '"');
header('Content-Transfer-Encoding: binary');
header('Accept-Ranges: bytes');
readfile($filename);
?>