[英]PHP forces PDF file download even though I'm using Content-Disposition: inline
我試圖在瀏覽器中顯示PDF - 如果可能的話 - 我知道我可以在Chrome中執行此操作,這正是我正在測試的。問題是,每次我嘗試時,它都會提示下載。
我正在使用PHP會話,所以我知道有一些無關的標題被發送,所以我調用了header_remove()
來重置所有內容。
我將此函數稱為顯示PDF:
<?php
// For demonstrative purposes
session_start();
if (!isset($_SESSION['auth'])) {
header('Location: login.php');
die;
}
/*
* void viewPDF (Report $report)
* Outputs the PDF of the report
*/
function viewPDF ($report) {
// Tell the browser we are going to serve a PDF file.
$file = dirname(__FILE__).'/../reports/'.$report->id.'.pdf';
// The location of the PDF
if (!file_exists($file)) {
die ('The PDF does not exist.');
// Somehow the file does not exist.
}
header_remove();
// I'm using PHP sessions, so remove the headers
// automatically set that might break something.
header('Content-Disposition: inline;filename='.$report->id.'.pdf');
header('Content-Transfer-Encoding: binary');
header('Content-Type: application/pdf');
header('Content-Length: '.filesize($file));
readfile($file);
// Serve the report PDF file from the reports
// repository.
die;
// Any whitespace could corrupt the PDF, so be extra
// sure nothing else gets printed.
}
// For demonstrative purposes:
$report = new StdClass;
$report->id = 1;
viewPDF($report);
?>
這些是發送的標頭:
Date: Tue, 08 Oct 2013 18:41:32 GMT
Server: Apache/2.2.22 (Win32) PHP/5.4.15
Content-Type: application/pdf
Content-Transfer-Encoding: binary
Content-Disposition: inline;filename=1.pdf
Connection: Keep-Alive
Keep-Alive: timeout=5, max=100
Content-Length: 73464
它仍然提示下載。 下載后,我可以在Adobe Reader中打開它。
我錯過了什么嗎?
謝謝。
這段代碼對我有用:
header('Content-Description: File Transfer');
header('Content-Type: application/pdf');
header('Content-Disposition: inline; filename="' . basename($file).'"');
header('Content-Transfer-Encoding: binary');
header('Expires: 0');
header('Cache-Control: must-revalidate');
header('Pragma: public');
header('Content-Length: ' . filesize($file));
ob_clean();
flush();
readfile($file);
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.