Home > Net >  Creating session with Codeigniter 3
Creating session with Codeigniter 3

Time:11-16

How I can set a session using a username if the login is successful? Also how to clear the session when the user is logged out. Thanks

It is a mine do login function. The log in is working fine and the database as well. I know it is not good code but I am just starting using PHP in Codeigniter 3.

    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');
}

}

It is my database check log in if the user and password exist.

  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;
    }

}

CodePudding user response:

    $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
    }    

to view your session

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

to logout or unset

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