codeIgniter如何在登录控制器中创建会话

时间:2016-11-25 11:30:13

标签: mysql codeigniter-3

如何创建登录会话名称?我试过了,但它对我没用。

这是我的代码:

loginModel

public function login($name, $pass){
    $this->db->select("username", "password");
    $this->db->from("users");
    $this->db->where("username", $name);
    $this->db->where("password", $pass);
    $query = $this->db->get();
    $ret = $query->row();
    if($query->num_rows() == 1){
        return true;
    }
    else {
        return false ;            
    }
}

loginControler;

    public function checkLogin(){        
    $this->form_validation->set_rules("username", "Username", "required");
    $this->form_validation->set_rules("password", "Password", "required");        
    if($this->form_validation->run() == false){            
        $this->load->view("login");            
    }
    else {            
        redirect("SiteCont/index");            
    }        
}

public function verifyUser(){
    $name = $this->input->post("username");
    $pass = $this->input->post("password");
    $this->load->model("loginModel");
    if($this->loginModel->login($name, $pass)){
        return true;
    }
    else {
         $this->form_validation->set_message("verifyUser", "geçersiz kullanıcı adı veya porala");
         return false;
   }

只有我需要一些东西;

if($this->session->userdata('name')){
    //show dashboard   
}
else {
    //show login
}

在登录页面中。

1 个答案:

答案 0 :(得分:0)

loginModel

public function login($name, $pass){
    $this->db->select("username", "password");
    $this->db->from("users");
    $this->db->where("username", $name);
    $this->db->where("password", $pass);
    $query = $this->db->get();
    $ret = $query->row();
    if($query->num_rows() == 1){
        //set the session data (you can add more values to array according to your needs)
            $data = array(
            'user_id' => $ret->user_id, //change your actual user id field
            );
        $this->session->set_userdata($data);
        //set the session data
        return true;
    }
    else {
        return false ;            
    }
}

检查

if($this->session->userdata('user_id')){
    //redirect to dashboard
}
else{
    //redirect to login
}

这将正常工作。根据您的需要更改变量名称。