使用codeigniter 3.X访问public_html外部的文件 [英] access file outside public_html using codeigniter 3.X
问题描述
出于安全原因,我将PDF文件放在public_html
外部的名为Pdf
的文件夹中.
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..
一个是:../../../../Pdf/{$name_hash}.pdf
.
另一个是:/home/xx/Pdf/{$name_hash}.pdf
One being:../../../../Pdf/{$name_hash}.pdf
.
The other being: /home/xx/Pdf/{$name_hash}.pdf
我试图包含该文件并将其作为js.openwindow以及readfile($filepath)
发送都无济于事!
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!
推荐答案
问题是您无法在浏览器URL中访问public_html
(或虚拟主机用于设置域的目录)后面的文件.您必须获取文件的内容并将其通过缓冲区发送到输出.您可以为此使用readfile($file)
PHP内置函数:
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";
}