Tutorial :How to verify if user is logged in?


I am using CodeIgniter framework for PHP. There are some pages that are exclusively for Admin and they are located in Admin/*. When the user logs in, i store some value in session as a flag and verify it in my controller to test whether the user is logged or not. I wrote the code to check session in every method in my controller. But, then I realized i didn't want to write the same line of code in each and every method since many issues are created from maintainability point of view. Then i decided to create a exclusive Controller which will load only Admin views and thus in it's constructor i check the session value. Is there any other method apart from this approach. Am i doing it right? Or any other secure mechanism is available in CodeIgniter?


You've taken one of the best approaches (my opinion), just make the other admin controllers extend from that controller so you can have specialized controllers (admin blog, admin gallery etc). If you need help, I'll gladly help you.


you could do it in your constructor method something like this,

function __construct {      parent::construct();      /* Do you login check here */  }  


For example:

class Admin extends Controller {     function __construct()   {       parent::__construct();        $this->is_logged_in();   }     function is_logged_in()   {       $is_logged_in = $this->session->userdata('is_logged_in');     if(!isset($is_logged_in) || $is_logged_in != true)      {       redirect('login');     }   }  

Note:If u also have question or solution just comment us below or mail us on toontricks1994@gmail.com
Next Post »