darkCoffy
darkCoffy

Reputation: 187

access file outside public_html using codeigniter 3.X

For security reasons I have the PDF files in a folder called Pdf located just outside the public_html.

Im trying to access this file from my controller which lies inside the application folder. I tried using a couple of paths..

One being:../../../../Pdf/{$name_hash}.pdf. The other being: /home/xx/Pdf/{$name_hash}.pdf

I tried to include the file and send it as an js.openwindow as well as readfile($filepath) all to no avail!

The files are existing and the name is also generated correctly by the hash functions so I'm sure its the path thats setting the problem.

Are there some rules of CI that i am not following for setting paths? Or is there any other solution to this.. Please help!

Upvotes: 1

Views: 1829

Answers (1)

Tpojka
Tpojka

Reputation: 7111

Thing is that you can't reach file behind public_html (or directory where virtual host sets the domain) within browser url. You have to get contents of file and send it through buffer to output. You can use readfile($file) PHP inbuilt function for that:

public function pdf()
{
    // you would use it in your own method where $name_hash has generated value
    $file = "/home/xx/Pdf/{$name_hash}.pdf";

    if (file_exists($file)) {
        header('Content-Description: File Transfer');
        header('Content-Type: application/pdf');
        // change inline to attachment if you want to download it instead
        header('Content-Disposition: inline; filename="'.basename($file).'"');
        header('Expires: 0');
        header('Cache-Control: must-revalidate');
        header('Pragma: public');
        header('Content-Length: ' . filesize($file));
        readfile($file);
    }
    else "Can not read the file";
}

PHP docs with example.

Upvotes: 2

Related Questions