开发者

How to set up protected static files in Kohana 3.1

开发者 https://www.devze.com 2023-03-11 08:16 出处:网络
I\'m using Kohana 3.1 with the ORM/Auth module enabled. I would like to serve static files (docs, pdfs, etc.) only to people with role A, in directory A_only.

I'm using Kohana 3.1 with the ORM/Auth module enabled. I would like to serve static files (docs, pdfs, etc.) only to people with role A, in directory A_only.

Since the .htaccess files just serves URLs that it finds directly and doesn't hand it off to index.php, I could deny all access in A_only through a .htaccess, bu开发者_如何转开发t then how would I serve the static files in a controller function?

I could also have an .htaccess in the A_only directory that requires authentication. However, this would require them to log in again even if I set it up to look in the database for user/passwords.


You're going to need to tell your web server to stop handling static files. The easiest solution would be to move the static files outside of the web directory so Apache can't find them; This will force that request to go through Kohana.

The second part is creating a controller which handles the permissions and file sending for you. The Kohana userguide has a fairly good example of something for to you work off:

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);
}

The main thing you need to worry about is changing where Kohana looks for the files:

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

The rest is boilerplate.

0

精彩评论

暂无评论...
验证码 换一张
取 消