...
CodeIgniter, Tutorials

How to use session in CodeIgniter?

18 December 2018

In this lession, we will learn that how can we use sessions in codeigniter.

Sessions

The Session class permits you maintain a user’s “state” and track their activity while they browse your site.
For using sessions, we need to load Session class in our controller.

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

Once library is loaded, the Sessions library object will be available using:

$this->session

Reading session data

Use $this->session->userdata(); method of session class to read session data.

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

we can also read a session data by using CodeIgniter Session Class

$this->session->item

Where an item is the name of the key you want to retrieve.

Creating a new session

set_userdata() method is used to create new session. This method takes an associative array for store values in session.

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

If you want to add one value at a time, set_userdata() also supports this syntax:

$this->session->set_userdata('some_name', 'some_value');

Removing Session Data

unset_userdata() method is used to remove a session data.

Examples:
Unset particular key

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

Unset an array of item keys

$array_items = array('username', 'email');
$this->session->unset_userdata($array_items);

Leave a Comments