Search code examples
phpcodeigniterauthenticationregistrationuserid

Codeigniter how to get userid after login


I have successfully created a registration and login system.
I have used useremail and password in the login form and I want to display the username and other properties related to that logged in user.

What are the simplest and best practices to get the userid after a login in codeigniter?


Solution

  • As good coder create session at login time and use session at website wide.

    public function login($username, $password) {
        $user = $this->db
            ->select("username, name, phone")
            ->where(
                 [
                    'username' => $username,
                    'password' => md5($password)
                 ]
             )
            ->get("table_name")
            ->row();
    
       if ($user) {
             $logindata = [
                 'userid' => $user->username,
                 'name'   => $user->name,
                 'phone'  => $user->phone
             ];
             $this->session
                  ->set_userdata($logindata);
             return true;
       }
       else {
             return false;
       }
    } 
    

    Then after you can use anywhere in website

    echo $this->session->userid;
    

    I hope it will help you in general way.