如何在Kohana 3.1中设置受保护的静态文件

时间:2011-06-08 02:28:33

标签: php kohana kohana-3 kohana-auth

我正在使用Kohana 3.1并启用了ORM / Auth模块。我想只在目录A_only中为角色为A的人提供静态文件(docs,pdf等)。

由于.htaccess文件只提供它直接找到的URL并且不会将其传递给index.php,我可以通过.htaccess拒绝A_only中的所有访问,但是我如何在一个.htaccess中提供静态文件。控制器功能?

我还可以在A_only目录中有一个需要身份验证的.htaccess。但是,这将要求他们再次登录,即使我将其设置为在数据库中查找用户/密码。

1 个答案:

答案 0 :(得分:3)

您需要告诉您的Web服务器停止处理静态文件。最简单的解决方案是将静态文件移到Web目录之外,以便Apache无法找到它们;这将迫使该请求通过Kohana。

第二部分是创建一个控制器,为您处理权限和文件发送。 Kohana用户指南有一个很好的例子可供您解决:

Line 247 of Controller_Userguide

// Get the file path from the request
$file = $this->request->param('file');

// Find the file extension
$ext = pathinfo($file, PATHINFO_EXTENSION);

// Remove the extension from the filename
$file = substr($file, 0, -(strlen($ext) + 1));

if ($file = Kohana::find_file('media/guide', $file, $ext))
{
    // Check if the browser sent an "if-none-match: <etag>" header, and tell if the file hasn't changed
    $this->response->check_cache(sha1($this->request->uri()).filemtime($file), $this->request);

    // Send the file content as the response
    $this->response->body(file_get_contents($file));

    // Set the proper headers to allow caching
    $this->response->headers('content-type',  File::mime_by_ext($ext));
    $this->response->headers('last-modified', date('r', filemtime($file)));
}
else
{
    // Return a 404 status
    $this->response->status(404);
}

您需要担心的主要问题是改变Kohana查找文件的位置:

if ($file = Kohana::find_file('media/guide', $file, $ext))

其余的是样板。