How to Authenticate User In Codeigniter PHP Framework

In this tutorial, am going to show you how you can authenticate user in Codeigniter php framework. I assume that you already have codeigniter installed and you can save and retreive user data (from a table).The following are needed for the implementation:
  1. User table (model)
  2. Base Controller
User Table
Create a method in the user model if one does not already exist which returns user data (object). Lets assume the method name is getById(). We will call this method return a user record by id.
User model example
    class User extends CI_Model
    {
        
        public $id ;
        
        public $name;
        
        public $email;
        
        public $password;


        /**
         * Get user by id
         * @param int $id
         * @return \User User object
         */
        public function getById($id = '')
        {
            
            $this->db->where(['id' => $id]);  
        
            $this->db->limit(1);

            $query =  $this->db->get('user');
            // initialze the data
            $data = $query->row_array();
            
            $user = new User();
            
            $user->id = $data['id'];
            $user->name = $data['name'];
            $user->email = $data['email'];
            $user->password = $data['password'];
         
            return $user;
        }
        
        
        
    }

 
Base Cotroller
Codeigniter allows you create your own base controller which other controllers can extend instead of CI controller. This controller should be placed under application/core folder.
This is where will place the login method to check if current user is logged in. This will allow other controllers authenticate user. The base controller implementation is as follows
	class My_Controller extends CI_Controller
        {
        
        
        /**
         *Holds  the current user object
         * @var User 
         */
        protected $current_user ;

        
        /**
         * Authenticate user
         * 
         * @param string $redirect_url Where to redirect user to if not already logged in
         * @return 
         */
        protected function _secure($redirect_url = 'users/login')
        {
            $this->_setCurrentUser();

            if($this->current_user && $this->current_use->id)
            {
                // user is already logged in
                return ;
            }
            // redirect user to login page
            redirect($redirect_url);


        }

        /**
         * This method get user data using the user model
         * It retrives the user id from the session 
         * 
         * @note user id must be saved in the session after user successfully login 
         */
        protected function _setCurrentUser()
        {
            if(!$this->current_user)
            {
                $this->load->library('session');
                $this->load->model('user');

                $user_id = $this->session->userdata('user_id') ;

                if($user_id)
                {
                    $this->current_user = $this->user->getById($user_id);
                }
            }

        }
          



    }

As you can see from above, two private methods are defined in the base controller, _secure() and _setCurrentUser(). The first method ensures that user is logged in by calling the second to retreve and set the $current_user property of the controller. It checks whether user property is set. If true, does nothing(user is logged) or else redirects user to loggin page.
Now we can start using _secure() method in our conrollers to ensure that only logged in users can access the endpoint/page.

Lest demonstrate that with an example controller
 
class Posts extends My_Controller
    {
        
        
        public function add_post()
        {
            
            $this->_secure();
            
            // the code to add post follows
        }
        
        
        
    }

I hope this helps someone!