I want to check if user is logged in CodeIgniter by using my library in the controller’s constructor.
This is my library:
class Administrator_libs {
public function validate_authen(){
if( $this->session->userdata('user_authen') ){
redirect(base_url().'admin/login/');
}
}
}
And this is my controller:
class Administrator extends CI_Controller {
public function __construct(){
parent::__construct();
$this->load->library('administrator_libs');
$this->administrator_libs->validate_authen();
$this->load->model('mod_menu');
}
}
But I get this error message:
Undefined property: Administrator_libs::$session
How can I use session in a library in CodeIgniter?
If you want to access any CodeIgniter library inside of your own, you must call
get_instance(). This is because$thisis bound to your current library and not the CodeIgniter object.Please see Creating Libraries CodeIgniter Documentation. Specifically the content under Utilizing CodeIgniter Resources within Your Library
This assumes you autoload the session library in
config/autoload.php, if not, you’ll also need to add$CI->load->library("session");after$CIinstantiation.IMPORTANT:
=&is not a typo. It’s passed by reference to save memory.