【问题标题】:How do I properly send a PDF file through PHP?如何通过 PHP 正确发送 PDF 文件?
【发布时间】:2013-01-07 04:32:55
【问题描述】:

我正在尝试发送 PDF 文件。这是正在执行的代码:

$file_path = '/path/to/file/filename.pdf'
$file_name = 'filename.pdf'

header("X-Sendfile: $file_path");
header("Content-type: application/octet-stream");
header("Content-Disposition: attachment; filename='$filename'");
readfile($file_path):

每当我直接下载文件时,都可以。但是,当我尝试通过此脚本下载文件时,下载的文件无法打开。我的 pdf 阅读器告诉我它无法打开“text/plain”类型的文件。我也尝试将 Content-type 设置为 application/pdf ,但我得到了同样的错误。我在这里做错了什么?

【问题讨论】:

  • 这很奇怪,前几天晚上我正在编写一个类似的脚本,header('Content-type: application/pdf'); 为我和readfile 一起工作。你确定路径正确吗?
  • 附带说明,您可能希望在标题行中使用$file_name,而不是在您的sn-p 中不存在的$filename
  • header(...; filename='$file_name'"); _。
  • 另外,确保您拥有该文件的权限可能是个好主意,并且使用is_readable 确实存在该文件,这只是一个提示,希望对您有所帮助!

标签: php pdf http-headers mime-types


【解决方案1】:

你试过了吗?

$file = '/path/to/file/filename.pdf';
header('Content-Disposition: attachment; filename="'. basename($file) . '"');
header('Content-Length: ' . filesize($file));
readfile($file);

使用readfile() 还可以消除您可能遇到的任何内存问题。

【讨论】:

    【解决方案2】:

    试试下面的代码。

    header("Content-Type: application/octet-stream");
    
    $file = "filename.pdf";
    header("Content-Disposition: attachment; filename=" . urlencode($file));   
    header("Content-Type: application/force-download");
    header("Content-Type: application/octet-stream");
    header("Content-Type: application/download");
    header("Content-Description: File Transfer");            
    header("Content-Length: " . filesize($file));
    flush(); // this doesn't really matter.
    $fp = fopen($file, "r");
    while (!feof($fp))
    {
        echo fread($fp, 65536);
        flush(); // this is essential for large downloads
    } 
    fclose($fp)
    

    如果上述方法对您没有帮助,请尝试以下方法

    header('Content-Description: File Transfer');
    header('Content-Type: application/octet-stream');
    header("Content-Type: application/force-download");
    header('Content-Disposition: attachment; filename=' . urlencode(basename($file)));
    // 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($file));
    ob_clean();
    flush();
    readfile($file);
    exit;
    

    get 请勿按要求设置文件路径$file_path

    【讨论】:

    • 为什么是三个Content-Type 标头?
    • 请注意,如果 PHP 作为 CGI 运行,flush() 不会做任何事情。
    • 我不会强制下载,甚至不会使用 PHP 流式传输数据 - 这种语言在数据类型方面非常不可靠,您可能会遇到错误和问题。如果您想提供下载,只需相应地设置您的网络服务器 - 这就是网络服务器的用途,它们将尽可能保证未修改且正确的交付。顺便说一句:我对 PHP 没有任何意见,我只知道它的优势、优势和劣势。如果您想保持专有数据完整,请不要使用 PHP
    • 以上代码为我完成了工作并帮助我完成了工作,所以我认为它也适用于其他人。
    • 为什么我的评论被删除了? “非常不可靠”:仅当您不知道自己在做什么时。
    猜你喜欢
    • 2013-01-06
    • 1970-01-01
    • 2015-05-24
    • 2019-05-25
    • 1970-01-01
    • 1970-01-01
    • 2020-08-21
    • 2011-05-20
    • 2016-01-15
    相关资源
    最近更新 更多