Handle session is very important when creating a member-based website where the user needs to register and login to their account to access website content.
With the help of a session, it is easier to identify the user and display the content accordingly.
In Codeigniter, require the loading session library to start work with Session. There are inbuilt methods are available that makes easier to handle session operations.
Contents
1. Load Library
There are two ways to load the library –
- Using autoload
- Loading on the controller
Using autoload
Open application/config/autoload.php
and add the session
in libraries array()
.
$autoload['libraries'] = array("session");
Loading on the controller
Created a application/controllers/user.php
file where defined a constructor function and load the session
library using $this->load->library()
method.
<?php defined('BASEPATH') OR exit('No direct script access allowed'); class User extends CI_Controller { public function __construct() { // Load session library $this->load->library('session'); } }
2. Set
To create session variable use $this->session->set_userdata()
. With this, you can either define one or multiple variables at a time.
Single variable
$this->session->set_userdata("username","yssyogesh");
Multiple variable
$data = array( "username" => "yssyogesh", "email" => "yogesh@makitweb.com", "user_id" => 2 ); $this->session->set_userdata($data);
3. Get
Specific variable
With userdata()
method you can read a session variable by passing its name e.g. username.
$username = $this->session->userdata('username');
All variable
To get all variable data don’t pass any value in the userdata()
method.
$this->session->userdata();
4. Destroy
Destroy single variable
Pass the name of the session variable in unset_userdata()
method to remove.
$this->session->unset_userdata('username');
Destroy all variable
The sess_destroy()
method clear all session variable.
$this->session->sess_destroy();
5. Flash data
Flashdata is a type of session data that will only available for the next request and automatically destroyed after that.
Create
To create flashdata use $this->session->set_flashdata()
method.
$this->session->set_flashdata('msg','Record updated successfully.');
Retrieve
Read the variable value using flashdata()
method. The userdata()
method does not work with flashdata to get the value.
$this->session->flashdata('msg');
6. Conclusion
It’s better to use autoload to load the session library because you don’t have the need to again load every time on each controller.
With flashdata you can temporarily create a variable that will only available for next request then it automatically gets destroyed.
If you found this tutorial helpful then don't forget to share.