Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Use session data in Hook in CodeIgniter 2.1.0

I am using CodeIgniter with version 2.1.0. I want to use Hooks for login authentication. That means I want in every controller check the session data if loggedin or not. So I want to use hooks. I do the following code for doing that:

In config file

$config['enable_hooks'] = TRUE;

In file hooks.php

$hook['post_controller_constructor'][] = array(
                               'class'    => 'SessionData',
                               'function' => 'initializeData',
                               'filename' => 'loginHelper.php',
                               'filepath' => 'hooks',
                               'params'   => array()
                               );

In file loginHelper.php

class SessionData{
    var $CI;

    function __construct(){
        $this->CI =& get_instance();
    }

    function initializeData() {

        // This function will run after the constructor for the controller is ran
        // Set any initial values here
        if (!$this->session->userdata('username')) { // This is line 13
            redirect('login');
        }
    }
}

But it throws the following error:

A PHP Error was encountered

Severity: Notice

Message: Undefined property: SessionData::$session

Filename: hooks/loginHelper.php

Line Number: 13

How can I solve this?

like image 239
Ariful Islam Avatar asked May 05 '26 12:05

Ariful Islam


1 Answers

"Called very early during system execution. Only the benchmark and hooks class have been loaded at this point..."

You should load all libraries and models manually that you use inside Hook:

if (!isset($this->CI->session))
{
    $this->CI->load->library('session');
}

And use $this->CI->session->userdata() instead of $this->session->userdata().

like image 75
safarov Avatar answered May 07 '26 03:05

safarov



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!