0

I'm getting a undefined index error when checking if a session exists. The error only occurs when a session does not exist.

Controller where the session is created:

$data = array(
                'email' => $this->input->post('email'),
                'is_logged_in' => TRUE
            );

$this->session->set_userdata($data);
redirect('site/index');

Controller where the check takes place:

$is_logged_in = $this->session->userdata['is_logged_in']; // error occurs here

if(!isset($is_logged_in) || $is_logged_in !== TRUE)
{
    $data['main_content'] = 'login_form';
    $this->load->view('includes/template', $data);
}

I've made sure the session library is loaded.

1
  • 1
    the exact error message is? Commented Dec 12, 2017 at 21:12

2 Answers 2

3

You are treating a method as an associative array. In codeigniter userdata is a function which returns the value of the index you pass it. So your line:

$is_logged_in = $this->session->userdata['is_logged_in'];

Should be:

$is_logged_in = $this->session->userdata('is_logged_in');
Sign up to request clarification or add additional context in comments.

Comments

1
$this->session->userdata['is_logged_in'];

Should be

$this->session->userdata('is_logged_in');

The difference is () instead of [] because userdata is a function, not an array.

Per the documentation

Retrieving Session Data

1 Comment

An alternate way to get session data is with this syntax $this->session->is_logged_in; Which will return NULL if that key does not exist the same as occurs with $this->session->userdata('is_logged_in');

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.