How to check is user login or not in codeigniter?

by cortez.connelly , in category: PHP CMS , 8 months ago

How to check is user login or not in codeigniter?

Facebook Twitter LinkedIn Telegram Whatsapp

1 answer

Member

by rollin , 8 months ago

@cortez.connelly 

In CodeIgniter, you can check if a user is logged in by accessing the session library and checking if a specific session variable is set. Here's how you can do it:

  1. Load the session library in your controller constructor:
1
$this->load->library('session');


  1. Check if the user is logged in by checking the session variable that you set when the user logs in:
1
2
3
4
5
6
7
if ($this->session->userdata('logged_in')) {
    // User is logged in
    // Add your code for logged in user here
} else {
    // User is not logged in
    // Add your code for guest users here
}


  1. You can also create a helper function that checks if the user is logged in:
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
function is_user_logged_in(){
   $CI = &get_instance();
   $CI->load->library('session');
   
   if ($CI->session->userdata('logged_in')) {
       return true;
   } else {
       return false;
   }
}


You can then call this function in your controllers or views to check if the user is logged in:

1
2
3
4
5
6
7
if (is_user_logged_in()) {
    // User is logged in
    // Add your code for logged in user here
} else {
    // User is not logged in
    // Add your code for guest users here
}


By following these steps, you can easily check if a user is logged in or not in CodeIgniter.