即使我使用Content-Disposition:inline,PHP也会强制下载PDF文件 [英] PHP forces PDF file download even though I'm using Content-Disposition: inline

查看:345
本文介绍了即使我使用Content-Disposition:inline,PHP也会强制下载PDF文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I'm trying to display a PDF in the browser if possible--and I know I can do this in Chrome, which is what I'm testing in. The trouble is, every time I try, it prompts a download instead.

我正在使用PHP会话,所以我知道有一些无关的标题被发送,所以我打电话给 header_remove()重置所有内容。

I'm using PHP sessions, so I know there are some extraneous headers being sent, so I called header_remove() to reset everything.

我调用此函数来显示PDF:

I call this function to show the 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中打开它。

It's still prompting a download though. Once it downloads, I can open it in Adobe Reader just fine.

我错过了什么吗?

谢谢。

推荐答案

此代码对我有用:

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

这篇关于即使我使用Content-Disposition:inline,PHP也会强制下载PDF文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆