CODEIGNITER:使用 readfile() 从控制器返回 PDF 文件

MyO*_*MyO 2 php pdf codeigniter

在我的 CODEIGNITER 项目之一中,我有以下运行良好的代码:

  $this->output
       ->set_content_type('application/pdf')
       ->set_output(file_get_contents($file));
Run Code Online (Sandbox Code Playgroud)

为了使代码内存友好,我想使用 php 函数readfile()代替file_get_contents()但它不能正常工作。

我注意到 readfile() 可以在我返回图像但不适用于PDF 时工作。

我怎么能做到这一点?

S. *_*Imp 5

readfile上的文档明确指出它只是将文件输出到浏览器。它只是将文件回显到标准输出并返回从文件中读取的字节数。如果要使用该函数,则必须不要使用 CodeIgniter 输出函数。您将需要使用更原始、更基本的 PHP 标头函数。像这样的东西:

$filepath = "/path/to/file.pdf";
// EDIT: I added some permission/file checking.
if (!file_exists($filepath)) {
    throw new Exception("File $filepath does not exist");
}
if (!is_readable($filepath)) {
    throw new Exception("File $filepath is not readable");
}
http_response_code(200);
header('Content-Length: '.filesize($filepath));
header("Content-Type: application/pdf");
header('Content-Disposition: attachment; filename="downloaded.pdf"'); // feel free to change the suggested filename
readfile($filepath);

exit; // this is important so that CodeIgniter doesn't parse any more output to ruin your file download
Run Code Online (Sandbox Code Playgroud)

注意:如果执行此代码的用户(您的用户、apache、www-data、httpd 等)无法读取 $filepath 上的权限,那么您可能会收到文件不可读错误。如果文件本身可读但它存在的目录不是,您也可以得到文件不存在错误。检查文件本身的权限以及该文件所在的目录。