CodeIgniter Basic Tutorial
Performance & Utilities
CodeIgniter Advanced
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.
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');
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);
// Get single data $username = $this->session->userdata('username'); // Get all session data print_r($this->session->all_userdata());
$this->session->set_userdata('username', 'NewName');
// Remove specific item $this->session->unset_userdata('email'); // Destroy all sessions $this->session->sess_destroy();
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');
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');
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