PHP 强制下载 PDF 文件,即使我使用的是 Content-Disposition : inline

标签 php pdf http-headers

如果可能的话,我正在尝试在浏览器中显示 PDF——我知道我可以在 Chrome 中执行此操作,这正是我正在测试的。问题是,每次我尝试时,它都会提示下载相反。

我正在使用 PHP session ,所以我知道发送了一些无关的 header ,所以我调用了 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);
?>

这些是正在发送的 header :

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

它仍然提示下载。下载后,我可以在 Adob​​e 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);

关于PHP 强制下载 PDF 文件,即使我使用的是 Content-Disposition : inline,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19255785/

相关文章:

ruby-on-rails - 用于图像的 Rails 自定义标题

php - 全栈与非全栈 MVC PHP 框架——有什么区别?

php - 如何在一个页面上运行多个ajax调用

php - Newsfeed Div 在第 2 页关闭

html - 如何在Firefox/IE/Chrome中使用浏览器显示ppt/doc/xls/pdf

python - 在 Django Rest FrameWork 中检索 HTTP header

java - Jersey/Grizzly POST 对于大 URI 失败

php - 在 MySQL php 中将 ID 从一个表插入到另一个表

pdf - Ghostscript pdf2jpg - 颜色错误?

java - 如何逐行阅读pdf