2017-04-03 81 views
1

我試圖在php應用程序中顯示.pdf文件。它在我的本地開發環境中很好地工作,但是在生產中,相同的代碼將pdf顯示爲亂碼文本。pdf文件顯示爲文本/ html而不是應用程序/ 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); 
?> 

這些都是根據鉻生產響應頭:

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的設置?

+2

只是爲了檢查:'%PDF-1.3':亂碼輸出的東西,如開始?您需要打開PHP中的錯誤報告。在發送標題之前查看是否有任何內容已經發送。 –

+0

可能有些代理或服務器正在改變它,或者您的請求改變標頭被PHP拒絕。檢查你的錯誤:http://stackoverflow.com/q/845021/1255289 – miken32

+0

是的,它從這樣的事情開始。生產中出現錯誤,打開它們進行調試是個好主意。 –

回答

-2

我認爲這是該行的錯誤:

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

注意小寫字母牛逼

此行應該是這樣的:

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

也注意到,你是使用$ _GET [「f」] 讀取文件是錯誤的,而是從$ 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); 
?> 
+0

不,它們不區分大小寫請參閱:RFC 2616 – nogad

+0

我也注意到並嘗試使用大寫T,它沒有任何區別。關於文件名變量,我不認爲它的問題,因爲我可以訪問該文件,問題是它顯示爲文本/ HTML。 –

+0

請注意,您正在嘗試讀取錯誤的文件 –