Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I use session in a library in CodeIgniter?

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?

like image 864
Chandara Sam Avatar asked Sep 10 '12 02:09

Chandara Sam


People also ask

How can use session variable 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.

How check session is set in CodeIgniter?

3 Answers. Show activity on this post. $this->session->set_userdata('some_name', 'some_value');

What is session in CodeIgniter?

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.

How can store session ID in database in CodeIgniter?

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`) );


1 Answers

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.

like image 131
Jordan Arseno Avatar answered Oct 11 '22 07:10

Jordan Arseno