MyO
MyO

Reputation: 443

CODEIGNITER: Return a PDF file from controller using readfile()

In one of my CODEIGNITER projects I have following code that is working nicely:

  $this->output
       ->set_content_type('application/pdf')
       ->set_output(file_get_contents($file));

To make code memory friendly I want to use the php function readfile() in place of file_get_contents() but its not working properly.

I have noted that readfile() works if I return an image but does not work with PDF.

How I can achieve this?

Upvotes: 2

Views: 8393

Answers (2)

S. Imp
S. Imp

Reputation: 2895

The documentation on readfile clearly states that it just outputs the file to the browser. It just echoes the file to stdout and returns the number of bytes read from the file. If you want to use the function, you'll have to NOT use the CodeIgniter output functions. You'll need to use the more raw, basic PHP header functions instead. Something like this:

$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

NOTE: If the permissions on $filepath are not readable to the user executing this code (your user, apache, www-data, httpd, etc.) then you might get a file is not readable error. You can also get a file does not exist error if the file itself is readable but the directory in which it exists is not. Check the permissions on the file itself and the directory in which that file resides.

Upvotes: 5

dhruv jadia
dhruv jadia

Reputation: 1680

Try below code if you are sure about mimetype of file

$contents = read_file($file);
    $this->output
            ->set_status_header(200)
            ->set_content_type('application/pdf')
            ->set_output($contents)
            ->_display();
    exit;

If you are not sure about the mimetype of file then

$this->load->helper('file');

$file = '/path/to/pdf/file';
$contents = read_file($file);

 $this->output
        ->set_status_header(200)
        ->set_content_type(get_mime_by_extension($file_path))
        ->set_output($contents)
        ->_display();

Reference:- https://codeigniter.com/user_guide/helpers/file_helper.html

Upvotes: -1

Related Questions