Search code examples
phpcodeigniterauthenticationcontrollerion-auth

How to make user object available across pages in CodeIgniter?


I'm fairly new to CodeIgniter and I'm using Ion Auth for user authorization. With the Ion Auth library, you get a user object like:

  $user = $this->ion_auth->get_user();
  echo $user->email;

If a user is logged in, I want the $user object to be available on any of the pages (in any of the controllers). How can I do this? (I'm using CodeIgniter 2)


Solution

  • This blog post of mine goes into a lot of detail in specifically using Ion_Auth to allow your entire application (including views) to access your current user's information.

    The short version... (specifically for the topic at hand)

    Adding this to your MY_Controller.php file

    class User_Controller extends CI_Controller {
    
        protected $the_user;
    
        public function __construct() {
    
            parent::__construct();
    
            if($this->ion_auth->logged_in()) {
                $data->the_user = $this->ion_auth->get_user();
                $this->the_user = $data->the_user;
                $this->load->vars($data);
            }
            else {
                redirect('/');
            }
        }
    }
    

    Then in your application just create your controller like this

    class App_Controller extends User_Controller {
    
        public function __construct() {
            parent::__construct();
        }
    
        function index() {
            //do stuff
        }
    }
    

    Then not only in your controller will you have access to $this->the_user but you will also have $the_user loaded into every view with $this->load->vars()