access file outside public_html using codeigniter 3.X

柔情痞子 提交于 2019-12-12 23:48:29

问题


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!


回答1:


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.



来源:https://stackoverflow.com/questions/38651094/access-file-outside-public-html-using-codeigniter-3-x

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!