简体   繁体   English

Codeigniter:routes.php中的会话类

[英]Codeigniter: session class in routes.php

How can I access the codeigniter session class inside routes.php? 如何访问routes.php中的codeigniter会话类?

I need that class to route all the request (except /login) to a certain controller, unless the user has admin privileges ( $this->session->userdata('logged') ). 我需要该类将所有请求(/ login除外)路由到某个控制器,除非用户具有管理员权限( $this->session->userdata('logged') )。

All the route rules are working, I only need to access that class. 所有路由规则都有效,我只需要访问该类。

You are not typically able to access the Singleton ($this->) from the config & routes file because the classes are not loaded at that point 通常,您无法从config&routing文件访问Singleton($ this->),因为此时尚未加载类

although there are a few workarounds to access the session, the better way would be to a MY_Controller & the _remap() function: 尽管有一些访问该会话的解决方法,但是更好的方法是使用MY_Controller和_remap()函数:

http://ellislab.com/codeigniter/user-guide/general/controllers.html#remapping http://ellislab.com/codeigniter/user-guide/general/controllers.html#remapping

Here's some sample code that explains a little more about how they work: 以下是一些示例代码,它们解释了它们的工作原理:

http://www.codebyjeff.com/blog/2012/11/ci-_remap-function-the-friend-you-never-knew-you-had http://www.codebyjeff.com/blog/2012/11/ci-_remap-function-the-friend-you-never-knew-you-had

Create this MY_Controller and store it in application/core/ , then have your other controllers extend it: 创建此MY_Controller并将其存储在application/core/ ,然后让其他控制器对其进行扩展:

<?php if (! defined('BASEPATH')) exit('No direct script access');

class MY_Controller extends CI_Controller {

function __construct() {
    parent::__construct();
    $this->_check_auth();
}

private function _check_auth(){
    if(!$this->session->userdata('is_admin')){
        $this->session->sess_destroy();
        redirect('login');
    }
}
}

Note: above code assumes you already have a user login system in place. 注意:上面的代码假定您已经有一个用户登录系统。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM