如何通过PHP正确发送PDF文件?
我正在尝试发送一个PDF文件。以下是正在执行的代码:如何通过PHP正确发送PDF文件?,php,pdf,http-headers,mime-types,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'"); rea
$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”类型的文件。我还尝试将内容类型设置为application/pdf
,但我得到了相同的错误。我做错了什么?请尝试下面的代码
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/to/file/filename.pdf';
header('Content-Disposition: attachment; filename="'. basename($file) . '"');
header('Content-Length: ' . filesize($file));
readfile($file);
使用还可以消除您可能遇到的任何内存问题。这很奇怪,前几天晚上我正在编写一个类似的脚本,header('Content-type:application/pdf')代码>为我使用了readfile
。您确定路径正确吗?请注意,您可能希望在标题行中使用$file\u name
,而不是在代码段中不存在的$filename
?标题(…;filename='$file\u name'))
另外,最好使用is_readable
确保您对该文件拥有权限,并且该文件确实存在,这只是一个提示,希望能有所帮助!为什么要使用三个内容类型
标题?请注意flush()
如果PHP作为CGI运行,则不会执行任何操作。我不会强制下载,甚至也不会使用PHP流式传输数据-这种语言在数据类型方面非常不可靠,您可能会遇到错误和问题。如果您想提供下载,只需相应地设置您的Web服务器-这就是Web服务器的用途,他们会这样做将尽可能保证未经修改和正确的交付。顺便说一句:我对PHP没有问题,我只知道它的优点、优点和缺点。如果你想保持专有数据完整,就不要使用PHP。以上代码为我做了工作,帮助我完成了工作,所以我认为它也适用于其他人。我的评论是什么被撤职?“高度不可靠”:除非你不知道自己在做什么。