CodeIgniter Laravel PHP Example Javascript jQuery MORE Videos New

Session with example CodeIgniter framework


In CodeIgniter or any other framework session is used to store information (in variables) and used it through out the application.

Initializing Session

To store data in session first of all we need to initialize the session.

In PHP we initialize the session by simply write the session_start(); function.

But in CodeIgniter We can do that by executing the following line in constructor.

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

Add data to session

In php we simply use $_SESSION super global variable to add value to a session.

$_SESSION[‘key’]=value;

Same thing can be done in CodeIgniter as shown below.

$this->session->set_userdata(‘session name', ‘any value’);

set_userdata() function takes two arguments. The first argument, session name, is the name of the session variable and here any value is the value assign to the session. We can use set_userdata() function to pass array to store values as shown below.

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

Remove Session Data

In PHP, we remove the data by using unset() function.
unset($_SESSION[‘some_name’]);

But in CodeIgniter we use unset_userdata() function that will remove data from session.

$this->session->unset_userdata(‘some_name');

If you want to remove more that one value and a array data then you can use the same function unset_userdata().

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

Fetch Session Data

After set a data to a session we also retrieve it for our use. Userdata() function will be used for this purpose.

$name = $this->session->userdata(‘name');