使用 Codeigniter 3 创建会话

Creating session with Codeigniter 3

如果登录成功,如何使用用户名设置会话?还有如何在用户注销时清除会话。谢谢

这是我做的登录功能。登录工作正常,数据库也正常。我知道这不是好的代码,但我刚开始在 Codeigniter 3 中使用 PHP。

    enter code here
public function dologin(){
$this->load->helper('url');
$this->load->model('user_model');
$username = $this->input->post("username");
$pass = $this->input->post("password");

$result = $this->user_model->checkLogin($username, $pass);
if ($result == 1) {
  redirect('messages/index');
} else {
  redirect('user/login');
}

}

如果用户和密码存在,就是我的数据库检查登录。

  enter code here
  public function checkLogin($username, $pass){
    $hash =sha1($pass);
    $this->db->from('Users');
    $this->db->where('username', $username);
    $this->db->where('password', $hash);

    $query=$this->db->get();
    
    if($query->num_rows() == 1){
        return true;
    }else{
        return false;
    }

}
    $result = $this->user_model->checkLogin($username, $pass);
// if data found in your database, then
    if ($result == 1) {
       $data = array(
            'user_id' => $result[0]['id'],
            'username' => $result[0]['username'],
            'is_logged_in' => true,
        );
        $this->session->set_userdata($data);
//your session has been created
    }    

查看您的会话

print_r($this->session->userdata());

注销或取消设置

$this->session->unset_userdata('user_id') == 'youruser_id');