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

GSt*_*Sto 3 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):
Run Code Online (Sandbox Code Playgroud)

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

Mar*_*Vry 5

你试过这个吗?

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

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