2014-05-12 43 views
0

在我的網站上,我允許管理員閱讀用戶的簡歷。這些簡歷存儲在根文件夾之外。爲了閱讀它們,我使用用戶的ID提交表單,從數據庫中獲取他們的簡歷路徑,並以PDF形式將其顯示在管理員的新選項卡中。以下是顯示PDF的代碼。POST變量導致閱讀PDF時出現問題

$file = "file_name.pdf"; 
$path = "C:/path/to/file/" . $file; 
header('Content-type: application/pdf'); 
header('Content-Disposition: inline; filename="' . $file . '"'); 
header('Content-Transfer-Encoding: binary'); 
header('Content-Length: ' . filesize($path)); 
header('Accept-Ranges: bytes'); 
readfile($path); 

爲了提交表單以獲得此代碼,我在javascript中執行以下操作。

$("#resume-user-id").val(ui.target.attr("id")); 
$("#resume-form").submit(); 

這裏是表單代碼。現在

<form id="resume-form" method="post" action="/account/profile/preview_resume.php" target="_blank"> 
    <input id="resume-user-id" type="hidden" name="user_id"></input> 
</form> 

,因爲我已經在文件名和路徑硬編碼的這一切工作只是很好,很正常,和PDF正確顯示。但是,只要我訪問post變量,PDF就不會加載。即使我保留文件名的硬編碼,並檢查是否使用isset函數設置後變量,一切都會中斷。該頁面看起來像它試圖加載PDF,但它只是繼續加載,加載和加載...

任何想法可能會導致這種情況?

--UPDATE--

我刪除了header('Accept-Ranges: bytes');線,而現在它工作正常(大部分)。這個標題究竟做了什麼,爲什麼會在這種情況下引發問題?我說「大部分」都很好,因爲除了我的測試PDF之外的所有工作。其中之一,但是,我只是收到一條消息,說:「無法加載PDF」...不知道這是爲什麼,或者它是如何與其他人不同。

+0

你是什麼'POST'ing? – ThomasEllis

+0

用戶標識。簡單地做isset($ _ POST ['user_id'])會破壞一切。 – Flyingcows00

+0

你是什麼意思'打破一切「?基於'user_id'的查詢是否正確返回,或PHP失敗或什麼?你是否能夠縮小問題發生的地點? – ThomasEllis

回答

1

好吧,我終於明白了。在更新原始問題後,我仍然遇到了大於1MB的PDF文件的一些錯誤。 Chrome不會顯示這些文件,IE(兼容模式)會破壞它們。在找到解決方案之前,我沒有在Firefox中測試它。我最後的劇本是這樣的:

header('Content-type: application/pdf'); 
header('Content-Disposition: inline; filename="' . $file . '"'); 
header('Content-Transfer-Encoding: binary'); 
header('Content-Length: ' . filesize($path)); 
header('Accept-Ranges: none'); 
ob_clean(); 
flush(); 
readfile($path); 

注意$文件是文件的名稱(即filename.pdf)和$ path是文件路徑(即C:/路徑/到/文件/ filename.pdf)。在最初的問題中,我在readfile調用之前添加了ob_clean();flush();,並將'Accept-Ranges'標頭設置爲'none'。

PDF文件現在可以在Chrome和IE(兼容模式)下查看。在Firefox中,文件實際上是下載的,但我並不擔心這一點。

類似的問題和答案在這裏找到:PHP stream PDF with fread and readfile produce a damaged pdf