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?
Add Session Data The same thing can be done in CodeIgniter as shown below. $this->session->set_userdata('some_name', 'some_value'); set_userdata() function takes two arguments. The first argument, some_name, is the name of the session variable, under which, some_value will be stored.
3 Answers. Show activity on this post. $this->session->set_userdata('some_name', 'some_value');
The Session class permits you to maintain a user's “state” and track their activity while they browse your site. CodeIgniter comes with a few session storage drivers, that you can see in the last section of the table of contents: Using the Session Class. Initializing a Session.
php or $this->load->library('session'); before use it. CREATE TABLE IF NOT EXISTS `ci_sessions` ( `id` varchar(40) NOT NULL, `ip_address` varchar(45) NOT NULL, `timestamp` int(10) unsigned DEFAULT 0 NOT NULL, `data` blob NOT NULL, KEY `ci_sessions_timestamp` (`timestamp`) );
If you want to access any CodeIgniter library inside of your own, you must call get_instance()
. This is because $this
is bound to your current library and not the CodeIgniter object.
$CI =& get_instance();
if( $CI->session->userdata('user_authen') ){
redirect(base_url().'admin/login/');
}
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 $CI
instantiation.
IMPORTANT: =&
is not a typo. It's passed by reference to save memory.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With