CodeIgniter - how to check the session that will be used with each method

Say my controller named Book , I have many methods like get_book(); read_book(); remove_book();

No methods in the class can be used without user login, and I can get user_id from the session.

My question is: what are / are the best ways to check if a user_id session is user_id so that I can use the methods?

I am currently thinking of creating an is_logged_in() method and applying it to all methods with an if-else statement, for example

 if($this->is_logged_in() { //do something } else { //redirect to home } 

Is it really long and tiring? Is there a better way to achieve this?

I read the link

codeigniter check user session in each controller

But it seems to me that I should still apply the is_logged_in check with each method.

Thanks for helping me!

+7
source share
3 answers

Create a file called MY_controller.php (the prefix can be edited in the configuration file) in /application/core :

 <?php if ( ! defined('BASEPATH')) exit('No direct script access allowed'); class MY_Controller extends CI_Controller { function __construct() { parent::__construct(); //Initialization code that affects all controllers } } class Public_Controller extends MY_Controller { function __construct() { parent::__construct(); //Initialization code that affects Public controllers. Probably not much needed because everyone can access public. } } class Admin_Controller extends MY_Controller { function __construct() { parent::__construct(); //Initialization code that affects Admin controllers IE redirect and die if not logged in or not an admin } } class Member_Controller extends MY_Controller { function __construct() { parent::__construct(); //Initialization code that affects Member controllers. IE redirect and die if not logged in } } 

Then anytime you create a new controller, you decide what access it requires

  class Book extends Member_Controller { //Code that will be executed, no need to check anywhere if the user is logged in. //The user is guaranteed to be logged in if we are executing code here. //If you define a __construct() here, remember to call parent::__construct(); } 

This reduces code duplication, because if you need a different member controller than Book , you can simply extend Member_Controller . Instead of doing checks in all of them.

+11
source

You do not have to do this. Just enter the verification code for entering the constructor, and you are all set!

 class Book extends CI_Controller { public function __construct() { if ($this->is_logged_in()) { // redirect to home } } public function get_book() { ... } // The rest of the code... } 
+9
source

You can use the method in the controller constructor, for example:

  if (! $ this-> session-> userdata ('logged_in'))
     {   
             redirect ('login');
     }

0
source

All Articles