How to create session in codeigniter?
session maintain user's "state" and to track their activity when they visit your website.
To use this class you need to first initialize or load the session library of CodeIgniter in your controller constructors or you can also go for $autoload in config file, so that it can be auto-loaded by the system.
To load session library manually use below code –
Syntax:
// load your session library in class constructor
$this->load->library('session');
OR
// you can add session library in autoload config file.
$autoload['libraries'] = array('session');
After loading the session library, you can simply use the session object as shown below.
$this->session
Add Session Data
$this->session->set_userdata('key', 'value');
set_userdata() function takes two arguments. The first argument, key, is the name of the session variable, under which, value will be stored.
set_userdata() function also supports another syntax in which you can pass array to store values as shown below.
$newdata = array(
'username' => 'mahtab',
'email' => 'mahtab.habib@itechtuto.com',
'logged_in' => TRUE
);
$this->session->set_userdata($newdata);
OR
$this->session->set_userdata('name', 'Your Name');
or
$this->session->set_userdata([
'name' => 'Your Name',
'email' => 'Your Email'
]);
If you want to add userdata one value at a time, set_userdata() also supports this syntax:
$this->session->set_userdata('key', 'value');
If you want to verify that a session value exists, simply check with isset():
// returns FALSE if the 'key' item doesn't exist or is NULL,
// TRUE otherwise:
isset($_SESSION['key'])
Or you can call has_userdata():
$this->session->has_userdata('key');
Fetch Session Data
After setting data in session, we can also retrieve that data as shown below. Userdata() function will be used for this purpose. This function will return NULL if the data you are trying to access is not available.
$name = $this->session->userdata('username');
OR
// Get all session data
$this->session->userdata();
How to print All Session Data
File Name :
print_r($_SESSION);
Remove Session Data
unset_userdata() function will remove only one variable from session.
File Name :
$this->session->unset_userdata('key');
If you want to remove more values from session or to remove an entire array you can use the below version of unset_userdata() function.
$this->session->unset_userdata($array_items);
$this->session->unset_userdata('name');
OR
$this->session->unset_userdata(['name', 'email']);
OR
unset($_SESSION['some_name']);
// or multiple values:
unset(
$_SESSION['some_name'],
$_SESSION['another_name']
);
function logout()
{
$this->session->sess_destroy();
//$this->session->unset_userdata('username');
redirect('user');
}
This method also accepts an array of item keys to unset:
$array_items = array('username', 'email');
$this->session->unset_userdata($array_items);
Check session exist or not
if ($this->session->has_userdata('name')) {
print $this->session->has_userdata('name');
}
If you want to verify that a session value exists, simply check with isset():
// returns FALSE if the 'some_name' item doesn't exist or is NULL,
// TRUE otherwise:
isset($_SESSION['key'])
OR
$loggedIn = $this->session->userdata('username');
if($loggedIn == TRUE){
$this->load->view('dashboard');
}
else
{
redirect('Home');
}
OR
$sess_id = $this->session->userdata('username');
if(!empty($sess_id))
{
$this->load->view('dashboard');
//redirect(site_url().'/reports');
}else{
$this->session->set_userdata(array('msg'=>''));
//load the login page
//$this->load->view('login/index');
redirect('Home');
}
Set Session Time
$config['sess_expiration'] = 'somevalue'; // here value in second
$config['sess_expiration'] = 0, if you want it to never expire.
$config['timeout_duration'] = 1800; // here value in second. (30 Minutes)
$sess_expiration = 7200; // Default Session Time 2 hours
Example :- Session_controller.php
<?php
class Session_controller extends CI_Controller {
public function index() {
//loading session library
$this->load->library('session');
//adding data to session
$this->session->set_userdata('name','Sana');
$this->load->view('session_view');
}
public function unset_session_data() {
//loading session library
$this->load->library('session');
//removing session data
$this->session->unset_userdata('name');
$this->load->view('session_view');
}
}
?>
session_view.php
<!DOCTYPE html>
<html lang = "en">
<head>
<meta charset = "utf-8">
<title>CodeIgniter Session Example</title>
</head>
<body>
Welcome <?php echo $this->session->userdata('name'); ?>
<br>
<a href = 'http://localhost:85/CodeIgniter-3.0.1/CodeIgniter3.0.1/index.php/sessionex/unset'>
Click Here</a> to unset session data.
</body>
</html>
Example :-
Following are some syntax that are mainly used for session data:-
To retrieve session data:
$this->session->userdata('item'); // Where item is the array index like session id
To add custom session data:
$this->session->set_userdata($array); // $array is an associative array of your new data
To retrieve all session data:
$this->session->all_userdata() // Read all session values
To remove all session data:
$this->session->unset_userdata('some_name'); // Removing values from session
Controller : session_tutorial.php
<?php
Class Session_Tutorial extends CI_Controller {
public function __construct() {
parent::__construct();
// Load form helper library
$this->load->helper('form');
// Load session library
$this->load->library('session');
// Load validation library
$this->load->library('form_validation');
}
// Show session demo page
public function session_demo_page_show() {
$this->load->view('session_view');
}
// Set values in session
public function set_session_value() {
// Check input validation
$this->form_validation->set_rules('session_value', 'Session Value', 'trim|required|xss_clean');
if ($this->form_validation->run() == FALSE) {
$this->load->view('session_view');
} else {
// Create session array
$sess_array = array(
'set_value' => $this->input->post('session_value')
);
// Add user value in session
$this->session->set_userdata('session_data', $sess_array);
$data['message_display'] = 'Value Successfully Set in Session';
$this->load->view('session_view', $data);
}
}
// Read session values
public function read_session_value() {
// Read all session values
$set_data = $this->session->all_userdata();
if (isset($set_data['session_data']) && $set_data['session_data']['set_value'] != NULL) {
$data['read_set_value'] = 'Set Value : ' . $set_data['session_data']['set_value'];
} else {
$data['read_set_value'] = 'Please Set Session Value First !';
}
$this->load->view('session_view', $data);
}
// Unset set values from session
public function unset_session_value() {
$sess_array = array(
'set_value' => ''
);
// Removing values from session
$this->session->unset_userdata('session_data', $sess_array);
$data['message_display'] = 'Successfully Unset Session Set Value';
$this->load->view('session_view', $data);
}
}
?>
views : session_view.php
<html>
<head>
<title>Session View Page</title>
<link rel="stylesheet" type="text/css" href="<?php echo base_url(); ?>css/style.css">
<link href='http://fonts.googleapis.com/css?family=Source+Sans+Pro|Open+Sans+Condensed:300|Raleway' rel='stylesheet' type='text/css'>
</head>
<body>
<div id="main">
<div id="note"><span><b>Note : </b></span> In this DEMO we gives you functionality to set your own session value. </div>
<div class="message">
<?php
if (isset($read_set_value)) {
echo $read_set_value;
}
if (isset($message_display)) {
echo $message_display;
}
?>
</div>
<div id="show_form">
<h2>CodeIgniter Session Demo</h2>
<?php echo form_open('session_tutorial/set_session_value'); ?>
<div class='error_msg'>
<?php echo validation_errors(); ?>
</div>
<?php echo form_label('Enter a session value :');?>
<input type="text" name="session_value" />
<input type="submit" value="Set Session Value" id='set_button'/>
<?php echo form_close(); ?>
<?php echo form_open('session_tutorial/read_session_value'); ?>
<input type="submit" value="Read Session Value" id="read_button" />
<?php echo form_close(); ?>
<?php echo form_open('session_tutorial/unset_session_value'); ?>
<input type="submit" value="Unset Session Value" id="unset_button" />
<?php echo form_close(); ?>
</div>
</div>
</body>
</html>
CSS : style.css
#main{
width:960px;
margin:50px auto;
font-family:raleway;
}
span{
color:red;
}
#note{
position:absolute;
left: 246px;
top: 81px;
}
h2{
background-color: #FEFFED;
text-align:center;
border-radius: 10px 10px 0 0;
margin: -10px -40px;
padding: 30px;
}
#show_form{
width:300px;
float: left;
border-radius: 10px;
font-family:raleway;
border: 2px solid #ccc;
padding: 10px 40px 25px;
margin-top: 70px;
}
input[type=text]{
width:100%;
padding: 10px;
margin-top: 8px;
border: 1px solid #ccc;
padding-left: 5px;
font-size: 16px;
font-family:raleway;
background-color: #FEFFED;
}
input[type=submit]{
width: 100%;
background-color:#FFBC00;
color: white;
border: 2px solid #FFCB00;
padding: 10px;
font-size:20px;
cursor:pointer;
border-radius: 5px;
margin-bottom: 15px;
}
.message{
position: absolute;
font-weight: bold;
font-size: 28px;
top:150px;
left: 862px;
width: 500px;
text-align: center;
}
.error_msg{
color:red;
font-size: 16px;
}
How to print all session variables currently set in codeigniter.
echo '<pre>' . print_r($_SESSION, TRUE) . '</pre>';
show all session variable currently set.
How to get Session Id
echo ses_id = session_id();
Previous
Next