Session is a global variable. This variable you can access in all pages. CodeIgniter session is a way to store information to be used across multiple pages. CodeIgniter Unlike a cookie, the information is not stored on the users computer.

Session creates on the server side where registered session variables and their values are stored. Session data store in server side .

Initializing a Session in codeigniter

CodeIgniter not load by default library,Session class manually in your controller constructor, use the $this->load->library() method in Codeigniter.

$this->load->library('session');

Once you loaded, the Sessions library object as shown below.

$this->session

Add Session Data

In PHP, we simply use $_SESSION array to set any data in session as follwing.

$_SESSION[‘key_name’] = value;

The same thing can be done in CodeIgniter as following.

$this->session->set_userdata('key_name', 'value');

As an alternative, the old method of assigning it as “userdata” is also available. In COdeIgniter you can add session data using set_userdata() method.

$newdata = array(
        'username'  => 'johndoe',
        'email'     => 'johndoe@some-site.com',
        'logged_in' => TRUE
);

$this->session->set_userdata($newdata);

Retrieve session

In Core PHP you can add session data using $_SESSION superglobal variable.

$_SESSION['key']

And for backwards compatibility, through the userdata() method in CodeIgniter.

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

If you want to verify that a session value exists, simply check with isset() in core php .

isset($_SESSION['key_name'])

Check sesison variale

If you want to verify that a session value exists, simpl3 check with has_userdata() in codeigniter.

$this->session->has_userdata('some_name');

Remove Session Data

In PHP you can remove data stored in session using the unset()

unset($_SESSION['key_name']);

In CodeIgniter, we can remove data stored in session using the unset_userdata()

$this->session->unset_userdata('key_name');

unset_userdata() method also accepts an array of item keys to unset:

$this->session->unset_userdata($array_items);

Destroying a Session

In Core PHP you can Destroy sesssion using session_destroy() function, or the sess_destroy() method in CodeIgniter.

session_destroy();

// or

$this->session->sess_destroy();