Codeigniter自定义用户角色仅打开特定页面

时间:2014-06-02 01:10:00

标签: php codeigniter user-roles

如何在CI打开特定页面中定义用户权限? 每次打开页面时我都在考虑调用数据库值,看看他是否有权打开特定页面。如果他没有权利会出现,它会直接将你退出。但是会有很多页要做。 我会创建一个函数,并在每次打开页面时检查它。 这是最简单的方法吗?

感谢。

1 个答案:

答案 0 :(得分:0)

你走在正确的轨道上。您可以在每个页面加载时查询数据库,这很好,如果值可能会更改,那么这是理想的。或者,您可以将权限数据保存到会话中,并在页面加载时查询会话(类似于您检查用户是否已登录的方式)。

  

但是会有很多页要做

您可以扩展默认的CI_Controller并添加在每个页面上运行的自己的代码。例如,在MY_Controller.php目录中创建一个名为application/core/的新文件,并将权限代码放入__construct()函数中,因此每次加载页面时都会自动运行。

<强>应用/核心/ MY_Controller.php

class MY_Controller extends CI_Controller
{
    function __construct()
    {
        parent::__construct();

        // Check privileges here. Something like..

        $this->load->helper('url');
        $this->load->model('privileges_model');

        $current_uri = uri_string(); 
            // If your url is something like http://some-site.com/blog/comments/123
            // this will return "/blog/comments/123"

        $user_id = $this->session->userdata('user_id');

        if($this->privileges_model->check($user_id, $current_uri) == FALSE)
        {
            // The user DOES NOT have the correct permissions.
            // Log them out, redirect them somewhere else, etc etc.
        }
    }
}

然后在您的控制器中,您可以扩展自定义CI_Controller,而不是扩展MY_Controller,将其方法继承到每个页面。

<强>应用/控制器/ secret.php

class Secret extends MY_Controller
{
    function __construct()
    {
        parent::__construct();
    }

    function index() 
    {
        // your secret page code here..
    }
}

Phil Sturgeon的这篇文章详细介绍了http://philsturgeon.co.uk/blog/2010/02/CodeIgniter-Base-Classes-Keeping-it-DRY