What are Sessions In CodeIgniter? How to read, write or remove session in CodeIgniter?

devquora
devquora

Posted On: Apr 25, 2024

 

Sessions in CodeIgniter

In CodeIgniter Session class allows you maintain a user’s “state” and track their activity while they are browsing your website.
In order to use session, you need to load Session class in your controller.

$this->load->library(‘session’); method is used to sessions in CodeIgniter

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

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

$this->session

Reading session data in CodeIgniter

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

Usage

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

You can also read a session data by using the magic getter of CodeIgniter Session Class

Usage

$this->session->item

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

Creating a session in CodeIgniter

Session’s Class set_userdata() method is used to create a session in CodeIgniter. This method takes an associative array containing your data that you want to add in session.

Example

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

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

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

Removing Session Data

Session’s Class unset_userdata() method is used to remove a session data in CodeIgniter. Below are example usages of same.

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

Read More https://www.codeigniter.com/userguide3/libraries/sessions.html

    Related Questions

    Please Login or Register to leave a response.

    Related Questions

    CodeIgniter Interview Questions

    How to check the version of CodeIgniter framework?

    How to check the version of CodeIgniter framework?..