1.

What are the sessions in CodeIgniter? How to handle sessions in CodeIgniter?

Answer»

In CodeIgniter, you are allowed to maintain a user’s “state” by Session class and keep an eye on their activity while they browse your website.

  • Loading a session in CodeIgniter:
    For using session, your controller should be loaded with your Session class by using the $this->load->library(‘session’);.
    Once the Session class is loaded, the Session library object can be obtained using $this->session.
  • Read session DATA in CodeIgniter:
    $this->session->userdata(); method of Session class is used to read or obtain session data in CodeIgniter.
    Usage: $this->session->userdata('name_of_user');
    Also, the below-given method of the Session class can be used to read session data.
    Usage: $this->session->key_item
    Where an ITEM represents the key name you want to access.
  • Create a session in CodeIgniter:
    The set_userdata() method that belongs to the Session class is useful in creating a session in CodeIgniter. This method uses an associative array that has the data you want to include in the session.
    Adding session data:
    Example:
$sessiondata = array( 'name_of_user' => 'lekha', 'email' => 'lekha@interviewbit.com', 'log_state' => TRUE);$this->session->set_userdata($sessiondata);

If you want to add a single user data at a TIME, set_userdata() supports this syntax:

$this->session->set_userdata('demo_username', 'demo_value');
  • Remove session data in CodeIgniter:
    The unset_userdata() method that belongs to the Session class is useful for removing session data in CodeIgniter. Usage examples are given below:
    Unset particular key:
$this->session->unset_userdata('name_of_user');

Unset an array of item keys:

$arr_items = array('name_of_user', 'email');$this->session->unset_userdata($arr_items);


Discussion

No Comment Found