The session class in CodeIgniter allows the user to maintain a user’s “state” and track their activity while browsing the website. The session can be initialized using the library and auto-loaded in the environment using the following command.
$this->load->library('session');
Set the session variable: Session indexes can be assigned using key-value pairs. A particular key can be assigned to a value using the assignment operator. The value may be a string, key, or even an array.
Syntax:
$_SESSION['key'] = value;
Example 1:
<?PHP // Starting a new session
session_start();
$_SESSION [ 'id' ] = 9 ;
// Check if the session name exists
if ( isset( $_SESSION [ 'id' ]) ) {
echo 'Session id is ' . $_SESSION [ 'id' ]. '<br>' ;
}
else {
echo 'Set the session id first ' . '<br>' ;
}
echo '<br>' ;
// Modifying the value of session
$_SESSION [ 'id' ] = -8 ;
echo 'New session id is ' . $_SESSION [ 'id' ]. '<br>' ;
?> |
Output:
Session id is 9 New session id is -8
The session value can also be assigned using the set_userdata() method in CodeIgniter. This method takes a key as the first argument and the. next is the value to be assigned.
Syntax:
set_userdata ('key' , value)
Multiple key-value pairs can also be added at the session index in CodeIgniter, indicated by the following code snippet.
Example 2:
<?php // Setting multiple key values
$sess_arr = array ( 'id' =>5, 'name' => 'yash' );
// Setting index at logged_in
$this ->session->set_userdata( 'logged_in' , $sess_arr );
// Printing the contents at this index
print_r( $_SESSION [ 'logged_in' ]);
?> |
Output:
Array ( [id] => 5 [name] => yash )
Unset the session variable: The session variable can be unset by assigning it to a NULL value. This destroys the value stored at this key value.
Syntax:
$_SESSION['ey'] = NULL
Example 3:
<?php // Starting a new session
session_start();
// Setting multiple values
$sess_arr = array ( 'id' =>5, 'name' => 'yash' );
$_SESSION [ 'logged_in' ]= $sess_arr ;
echo ( 'Old session : ' );
print_r ( $_SESSION [ 'logged_in' ]);
echo '</br>' ;
// Unsetting the value
$_SESSION [ 'logged_in' ]= NULL;
echo ( 'New session? : ' );
print_r ( $_SESSION [ 'logged_in' ]);
?> |
Output:
Old session : Array ( [id] => 5 [name] => yash ) New session? :