如何使用PHP强制下载PDF文件?

时间:2020-03-25 05:27:11

标签: php downloadfile

我一直试图在浏览器中强制下载PDF文件,但我成功完成了此操作,正在下载文件。但是,当我打开下载的PDF时,它们无法正确显示,诸如解码或无法正确看到字体和图像之类的东西,而不是显示一些奇怪的文本和图标。这是我用来下载文件的代码:

 //Here I am getting the complete path to pdf file
 $file_url  = stripslashes( trim( $theFile ) );
 //get filename
 $file_name = basename( $theFile );
 //get fileextension    
 $file_extension = pathinfo($file_name);
 //security check
 $fileName = strtolower($file_url);

 //var_dump($file_url, $file_name, $file_extension); die();
 //var_dump($file_name); die();

 $file_new_name = $file_name;


 header("Expires: 0");
 header("Cache-Control: no-cache, no-store, must-revalidate");
 header('Cache-Control: pre-check=0, post-check=0, max-age=0', false);
 header("Pragma: no-cache");
 header("Content-type: application/pdf");
 header("Content-Disposition:attachment; filename={$file_new_name}");
 header("Content-Type: application/force-download");

 readfile("{$file_url}");

 exit();

我想在此代码中添加其他内容来解决此问题吗?

1 个答案:

答案 0 :(得分:1)

关注PHP document

Note:
readfile() will not present any memory issues, even when sending large files, on its own.
If you encounter an out of memory error ensure that output buffering is off with ob_get_level().

此链接PHP readfile() causing corrupt file downloads,删除第一行中打开的PHP标记(<?php)之前的所有空格。

简而言之,空格会破坏您的二进制文件。

<?php
...
// clean all levels of output buffer
while (ob_get_level()) {
    ob_end_clean();
}
readfile("{$file_url}");

exit();