PHP未在Google Chrome中显示PDF文件


PHP not displaying PDF file in Google Chrome

我想用这个代码在浏览器中显示PDF文件

<?php
    $file = './path/to/the.pdf';
    $filename = 'Custom file name for the.pdf'; /* Note: Always use .pdf at the end. */
    header('Content-type: application/pdf');
    header('Content-Disposition: inline; filename="' . $filename . '"');
    header('Content-Transfer-Encoding: binary');
    header('Content-Length: ' . filesize($file));
    header('Accept-Ranges: bytes');
    @readfile($file);
?>

该代码在Firefox中运行良好,但在Chrome中则不然。我还没有在任何其他浏览器中进行过测试。这是Chrome的错误吗?我有没有办法让它在Firefox和Chrome中显示?

只需将内容处理更改为附件

 header('Content-Disposition: attachment;; filename="' . $filename . '"');

这不会在浏览器中显示PDF,但在Chrome中它似乎可以工作。

这取决于您的浏览器设置,而不是代码。通常默认情况下,firefox会在浏览器中打开pdf,而在chrome 的情况下则不然

我以前也遇到过同样的问题,但并不是所有的计算机都有这个问题。在我的情况下,我使用Adobe或默认的Chrome PDF阅读器进行了一些设置。检查您的设置。

$file是否只是没有文件名本身的文件路径?在这种情况下,你应该使用吗

header('Content-Length: ' . filesize("$file/$filename"));