正确的PHP标头下载pdf文件

use*_*too 65 php pdf header

当用户点击链接时,我真的很难让我的应用程序打开pdf.

到目前为止,锚标记重定向到一个页面,该页面发送以下标题:

$filename='./pdf/jobs/pdffile.pdf;

$url_download = BASE_URL . RELATIVE_PATH . $filename;


header("Content-type:application/pdf");



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

readfile("downloaded.pdf");
Run Code Online (Sandbox Code Playgroud)

这似乎不起作用,有没有人过去成功地解决了这个问题?

gat*_*gat 118

w3schools上的示例2 显示了您要实现的目标.

<?php
header("Content-type:application/pdf");

// It will be called downloaded.pdf
header("Content-Disposition:attachment;filename='downloaded.pdf'");

// The PDF source is in original.pdf
readfile("original.pdf");
?>
Run Code Online (Sandbox Code Playgroud)

还要记住,

重要的是要注意在发送任何实际输出之前必须调用header()(在PHP 4及更高版本中,您可以使用输出缓冲来解决此问题)

  • 记住要删除文件名周围的单引号。如果您使用filename ='downloaded.pdf',则某些浏览器将尝试使用文件名中的引号保存文件。我最近在OSX上经历了这种情况。 (2认同)

小智 24

$name = 'file.pdf';
//file_get_contents is standard function
$content = file_get_contents($name);
header('Content-Type: application/pdf');
header('Content-Length: '.strlen( $content ));
header('Content-disposition: inline; filename="' . $name . '"');
header('Cache-Control: public, must-revalidate, max-age=0');
header('Pragma: public');
header('Expires: Sat, 26 Jul 1997 05:00:00 GMT');
header('Last-Modified: '.gmdate('D, d M Y H:i:s').' GMT');
echo $content;
Run Code Online (Sandbox Code Playgroud)

  • 请注意,将整个文件内容加载到变量中可能会与内存限制发生冲突。这就是为什么“readfile()”是首选解决方案。 (3认同)

小智 8

我最近遇到了同样的问题,这对我有帮助:

    header('Content-Description: File Transfer'); 
    header('Content-Type: application/octet-stream'); 
    header('Content-Disposition: attachment; filename="FILENAME"'); 
    header('Content-Transfer-Encoding: binary'); 
    header('Expires: 0'); 
    header('Cache-Control: must-revalidate, post-check=0, pre-check=0'); 
    header('Pragma: public'); 
    header('Content-Length: ' . filesize("PATH/TO/FILE")); 
    ob_clean(); 
    flush(); 
    readfile(PATH/TO/FILE);      
    exit();
Run Code Online (Sandbox Code Playgroud)

我在这里找到了这个答案

  • ob_start(); 在顶部确保数据损坏 (3认同)

Hav*_*ard 6

您的代码中需要考虑一些事项.

首先,正确编写这些标题.你永远不会看到任何服务器发送Content-type:application/pdf,标题Content-Type: application/pdf,间隔,大写的第一个字母等.

在文件名中Content-Disposition仅是文件名,而不是完整路径,并altrough我不知道,如果它的强制性与否,这个名字来源于包裹在"'.此外,你的最后一个'失踪.

Content-Disposition: inline暗示文件应该显示,而不是下载.请attachment改用.

此外,将文件扩展名设为大写,以使其与某些移动设备兼容.

总而言之,您的代码看起来应该更像这样:

<?php

    $filename = './pdf/jobs/pdffile.pdf';

    $fileinfo = pathinfo($filename);
    $sendname = $fileinfo['filename'] . '.' . strtoupper($fileinfo['extension']);

    header('Content-Type: application/pdf');
    header("Content-Disposition: attachment; filename=\"$sendname\"");
    header('Content-Length: ' . filesize($filename));
    readfile($filename);
Run Code Online (Sandbox Code Playgroud)

Content-Length是可选的,但如果您希望用户能够跟踪下载进度并检测下载是否中断,这也很重要.但在使用它时,您必须确保不会随文件数据一起发送任何内容.确保之前<?php或之后绝对没有?>,甚至没有空行.

  • 你不需要结束标签`?>`.在这种情况下,最好将其删除. (3认同)