尽管我使用 Content-Disposition: inline,但 PHP 仍然强制 PDF 文件下载

4
我想在浏览器中显示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中正常打开。

我是不是缺少了什么?

谢谢。


并不是每个人都喜欢在浏览器中查看PDF文件(比如我)。我宁愿将其下载并单独查看/打开。如果已经配置为不允许浏览器内联查看文件,则无法强制浏览器内联查看该文件。 - Marc B
尝试在readfile之前添加以下内容:header('Accept-Ranges: bytes'); - Mehdi Karamosly
@MarcB:用户有两个选项,但客户希望可以从浏览器中查看。我可以直接在Chrome浏览器中访问PDF文件。这一定是一个头部问题,因为如果我可以使用Chrome查看任何PDF文件,那么我一定能够模拟查看任何其他PDF文件...我需要将REQUEST_URI更改为PDF文件扩展名吗?那会很麻烦... - M Miller
@MehdiKaramosly:我确实尝试过了,但没有任何区别。 - M Miller
不知道该怎么解决,Marc B 可能是对的。 - Mehdi Karamosly
1个回答

6

这段代码对我有效:

    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);

哎呀,还是不行啊。我甚至尝试过删除会话、清除头文件,并完全按照你的代码使用…… - M Miller
你用的是哪个浏览器?我试过Chrome和IE,都非常好用。 :) - Mehdi Karamosly
1
我真的不知道这是怎么发生的,但是我的Chrome PDF阅读器插件和Adobe Reader插件都在Chrome浏览器中被禁用了。但是现在一切都恢复正常了!非常感谢。 - M Miller

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接