如何通过PHP正确发送PDF文件?

时间:2013-01-23 16:09:24

标签: php pdf http-headers mime-types

我正在尝试发送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,但我得到了相同的错误。我在这里做错了什么?

2 个答案:

答案 0 :(得分:2)

你试过这个吗?

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

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

答案 1 :(得分:1)

尝试以下代码。

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;

不要根据需要设置文件路径$file_path