如何检查用户是否是管理员而不是普通用户?

时间:2014-12-23 20:21:58

标签: php codeigniter

首先,继承我的代码:

<?php
class Admin extends CI_Controller {

public function __construct()
{
    parent::__construct();
    $this->load->model('admin_model');
}

 function logout()
{
$this->session->unset_userdata('logged_in');
session_destroy();
redirect('home', 'refresh');
}    

public function index()
  {
   if($this->session->userdata('logged_in'))
 {
$session_data = $this->session->userdata('logged_in');
if  ($session_data['id'] != 1){
    $this->load->view('head');
    echo "Sorry, you have to be an administrator to access this page";
    $this->load->view('footer');

} else {
$session_data = $this->session->userdata('logged_in');
$data['username'] = $session_data['username'];
$this->load->view('head');
$this->load->model('admin_model');
$data['users'] = $this->admin_model->show_data(); 
$data['bikes'] = $this->admin_model->show_bikes();
$this->load->view('admin', $data);
$this->load->view('footer');

}
} else
{
 redirect('login', 'refresh');
}

}

我所处的困境是,是的,这将阻止所有正常用户访问管理/索引页面。但是他们仍然可以访问admin / create,admin / update等,除非我在所有需要一些时间的函数上添加if语句。有没有更快的方法(可能我可以放在构造中)将检查应用于所有管理页面?感谢

1 个答案:

答案 0 :(得分:0)

只需将管理员检查代码移至构造函数:

<?php
class Admin extends CI_Controller {

public function __construct()
{
    parent::__construct();

    if(!$this->session->userdata('logged_in')) {
        redirect('login', 'refresh');
    }
    if  ($session_data['id'] != 1){
        $this->load->view('head');
        echo "Sorry, you have to be an administrator to access this page";
        $this->load->view('footer');
        exit; // or return? sorry, not too familiar w/ CodeIgniter
    }

    $this->load->model('admin_model');
}

...

public function index()
{    
    ...
}