CodeIgniter restricted page for admin users only CodeIgniter restricted page for admin users only codeigniter codeigniter

CodeIgniter restricted page for admin users only


In your login function :

//set the session variables$sessiondata = array('user' => $usr_result); //This you'll be able to access all your user info at anytime.$this->session->set_userdata($sessiondata);

And in your main controller :

if ($this->session->userdata('user') && $this->session->userdata('user')->is_admin == "Yes")

or, more readable :

$myUser = $this->session->userdata('user');if ($myUser && $myUser->is_admin == "Yes")

You don't need to set 'loginuser' => TRUE. If there is a session, it's because your user is logged in. So you just have to check if the session is set or not to know if your user is logged in or not.


If you want to set it for all actions in the controller, add this contructor to your Controller

//If you want to have the user into a variableprivate $currentUser; public function __construct(){  $this->load->model('login_model');  $username = $this->session->userdata('username');  $usr_result = $this->login_model->get_user_by_username($username);  if(!$usr_result->admin)    die; //or redirect to page not available  //If you want to have the user into a variable  $this->currentUser = $usr_result;}

Into your login_model create a new method get_user_by_username which will return the user by its username. If you don't have unique usernames, add the id of the user in the session and create a method in your model named get_user_by_id which will return the user by its id.

Hope it is what you are looking for. This way you don't have to set the admin session.

L.E. To what Steven said, modify it like this:

$sessiondata = array(          'username' => $username,          'loginuser' => TRUE,          'admin' => $usr_result->admin);


You need to save the admin result to the session data array

So if the user is an admin you would just add

 if($usr_result->admin == 'YES'){      $admin = true; }else{      $admin = false; } $sessiondata = array(              'username' => $username,              'loginuser' => TRUE,              'admin' => $admin         );

Then you would just check for it on the next page

 if ($this->session->userdata('admin')){