【问题标题】:Creating session with Codeigniter 3使用 Codeigniter 3 创建会话
【发布时间】:2021-12-25 13:45:31
【问题描述】:

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

这是一个我的登录功能。登录工作正常,数据库也正常。我知道这不是好的代码,但我刚刚开始在 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;
    }

}

【问题讨论】:

  • 我建议不要重新发明轮子,而是将像 ion-auth 这样的身份验证库与您的项目集成
  • Codeigniter 3 确实过时了,建议你从 codeigniter 4 入手。

标签: php codeigniter


【解决方案1】:
    $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');

【讨论】:

    猜你喜欢
    • 2017-03-08
    • 2016-04-01
    • 2015-07-07
    • 2015-04-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多