使用 codeigniter 3.X 访问 public_html 之外的文件

access file outside public_html using codeigniter 3.X

出于安全原因,我将 PDF 文件放在 Pdf 文件夹中,该文件夹位于 public_html.

之外

我正在尝试从位于应用程序文件夹内的控制器访问此文件。 我尝试使用几个路径..

一个是:../../../../Pdf/{$name_hash}.pdf。 另一个是:/home/xx/Pdf/{$name_hash}.pdf

我尝试包含该文件并将其作为 js.openwindow 以及 readfile($filepath) 发送,但都无济于事!

文件存在并且名称也由哈希函数正确生成,所以我确定它是设置问题的路径。

是否有一些 CI 的规则我没有遵循来设置路径?或者有没有其他解决办法..请帮助!

问题是您无法在浏览器 url 中访问 public_html 后面的文件(或虚拟主机设置域的目录)。您必须获取文件的内容并将其通过缓冲区发送到输出。您可以为此使用 readfile($file) PHP 内置函数:

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.