如何在代码点火器中使用会话创建权限

时间:2013-09-11 10:23:18

标签: php codeigniter

我在创建权限菜单时遇到问题,

我有一个桌面用户..

用户名,密码,权限。

我在这样的模型中有一个函数..

function valid_login($username, $password)
        {
        $query = $this
            ->db
            ->where('username', $username) 
            ->where('password', md5($password)) 
            ->limit(1) 
            ->get('user'); /

        if ($query->num_rows() == 1) {
                return $query->row_array(); 
        }
        else
                {
                        return FALSE; 
                }
        }

来自控制器的值发布,像这样的脚本..

public function index()
        {
              if ( isset($_SESSION['permission']) ) { 
                 redirect('home_controller/home'); 
              }

              $this->load->library('form_validation'); 
              $this->form_validation->set_rules('username', 'Username', 'required'); 
              $this->form_validation->set_rules('password', 'Password', 'required|min_length[4]');
              if ( $this->form_validation->run() == TRUE ) { 
                 $this->load->model('m_user'); 
                 $result = $this->m_user->valid_login(
                             $this->input->post('username'),  
                             $this->input->post('password')
                          );

                        if ($result == TRUE) { 
                        $_SESSION['permission'] = ????;
                            redirect('home_controller/home'); 
                        }
              } 

                $this->load->view('login_form'); 
        }

我不明白,如何从模型中获取字段权限值。我需要该值来创建$ _SESSION ..

myView就像这样......

<?php
if($_SESSION['permission']=="Administrator"){
    $this->load->view('administrator_menu');;
}else{
    $this->load->view('user_menu');;
}
?>

感谢您的关注.. 任何人都可以帮助我..

1 个答案:

答案 0 :(得分:1)

像这样设置CI中的会话:

if ($result == TRUE) { 
    print_r( $result );die;
    //$this->sesson->set_userdata('logged_user', $result); #this to set the session with the returned result
    $_SESSION['permission'] = $result['permission'];  #set permission from the result in the session
    redirect('home_controller/home'); 
}

现在读取会话是否存在或不这样做:

if( $this->session->userdata('logged_user') ){
    echo "The user id stored in session is :".$id = $this->session->userdata['logged_user']['id'];
}else{
    redirect('someplace', 'refresh');
}

编辑:
要开始会话,首先在application / autoload.php中自动加载它:

$autoload['libraries'] = array('session');

其次在encryption key中设置一个随机application/config.php,如下所示:

$config['encryption_key'] = 'xxxxxxxxxxxxxxxxxxxxxxxxxxxxx';