如何在Codeigniter中限制对文件夹中文件的访问

Pra*_*shi 4 security .htaccess codeigniter robot

您好,我使用codeigniter开发了我的网站,但是当我在google中搜索我的网站时,google会显示指向特定文件夹中文件(pdf)的链接,并且用户无需登录即可直接查看这些文件(pdf)。我想限制Google直接显示指向这些文件的链接。例如:www.mywebsite / myfolder / myfile

请指导我如何完成此任务。谢谢。

Arj*_*Raj 5

对之前的答案做了一些修改:

将.htaccess放置在内容所在的文件夹中

order deny, allow
deny from all
Run Code Online (Sandbox Code Playgroud)

这将拒绝所有对该特定文件夹的访问。

要访问文件,请在带有主体的控制器中编写一个函数-

public function index($file_name){
    if($this->login())  // login check
        if (preg_match('^[A-Za-z0-9]{2,32}+[.]{1}[A-Za-z]{3,4}$^', $file_name)) // validation
            {
            $file = 'my_path/'.$file_name;
            if (file_exists($file)) // check the file is existing 
                {
                header('Content-Type: '.get_mime_by_extension($file));
                readfile($file);
                }
            else show_404()
            }
    else    show_404();
}
Run Code Online (Sandbox Code Playgroud)

那么您必须像这样在配置文件夹中的routes.php文件中添加一些行

$route['my_files/(:any)'] = "my_controller/index/$1";
Run Code Online (Sandbox Code Playgroud)

这会将所有请求重定向到myfiles / bla_bla_bla到my_controller / index / bla_bla_bla

认为这可能会有所帮助:)


Lau*_*nce 0

基本上,您需要将文件托管在 public_html 文件夹之外 - 而是通过 php readfile() 将它们提供给用户。

像这样的东西会起作用

function user_files($file_name = "")
{
    // Check if user is logged in
    if($this->user->logged_in())
        {   
            // Now check the filename is only made up of letters and numbers
            // this helps prevent against file transversal attacks
            if (preg_match('^[A-Za-z0-9]{2,32}+[.]{1}[A-Za-z]{3,4}$^', $file_name)))
            {
                // Rewrite the request to the path on my server 
                $file = '../my_folder/'.$file_name;

                // Now check if file exists
                if (file_exists($file))
                {
                   // Serve the file
                   header('Content-Type: '.get_mime_by_extension($file));
                   readfile($file);
               }
            }
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

注意:您需要小心目录遍历 - 因此您应该进行一些检查以确保文件名仅由字母组成