Advertisement
Google Ad Slot: content-top
CodeIgniter Session Management
Sessions are used to store user-specific data that can be accessed across multiple pages.
For example, when a user logs in, we use sessions to remember their login status, username, or preferences until they log out or the session expires.
CodeIgniter provides a Session Library to handle this easily.
🔹 Step 1: Load the Session Library
CodeIgniter automatically loads the session library if enabled in autoload.php.
Open application/config/autoload.php:
$autoload['libraries'] = array('session');
If not autoloaded, you can load it in your controller:
$this->load->library('session');
🔹 Step 2: Storing Session Data
You can store session data as an array:
// Set session data
$userdata = array(
'username' => 'JohnDoe',
'email' => 'john@example.com',
'logged_in' => TRUE
);
$this->session->set_userdata($userdata);
🔹 Step 3: Retrieving Session Data
// Get single data
$username = $this->session->userdata('username');
// Get all session data
print_r($this->session->all_userdata());
🔹 Step 4: Updating Session Data
$this->session->set_userdata('username', 'NewName');
🔹 Step 5: Removing Session Data
// Remove specific item
$this->session->unset_userdata('email');
// Destroy all sessions
$this->session->sess_destroy();
🔹 Step 6: Flashdata (Temporary Session Data)
Flashdata is session data that only lasts for the next request, usually for messages like success/error alerts.
// Set flashdata
$this->session->set_flashdata('success', 'User registered successfully!');
// Get flashdata
echo $this->session->flashdata('success');
🔹 Step 7: Tempdata (Session with Expiry Time)
You can also store data that expires after a specific time:
// Set tempdata (expires in 5 seconds)
$this->session->set_tempdata('promo', 'Discount applied!', 5);
// Get tempdata
echo $this->session->tempdata('promo');
🔹 Step 8: Session Configuration
Session settings are defined in application/config/config.php:
$config['sess_driver'] = 'files'; // or 'database' $config['sess_cookie_name'] = 'ci_session'; $config['sess_expiration'] = 7200; // 2 hours $config['sess_save_path'] = sys_get_temp_dir(); // for file driver