Get session data in codeIgniter; In this tutorial, you will learn how to get session data on controller and views in codeIgniter 4, 3.
How to Get Session Data in CodeIgniter
Here are steps to get session data on controllers and views in CodeIgniter
- Step 1: Start a Session
- Step 2: Set Session Data
- Step 3: Get Session Data in Controller
- Step 4: Pass Session Data to Views
- Step 5: Display Session Data in Views
Step 1: Start a Session
Before getting session data, it is important to add the session library in your controller constructor or autoload.php file.
$this->load->library('session');
Step 2: Set Session Data
To set session data, you can use the set_userdata() method of the session library. For example, let’s say you want to set the user’s name in the session data.
$this->session->set_userdata('username', 'John');
Step 3: Get Session Data in Controller
To get session data in the controller, you can use the userdata() method of the session library. For example, to get the user’s name from the session data:
$username = $this->session->userdata('username');
Step 4: Pass Session Data to Views
To pass session data to views, you can use the second parameter of the $this->load->view() method. For example, let’s say you want to pass the user’s name to the header view:
$data['username'] = $this->session->userdata('username');
$this->load->view('header', $data);
Step 5: Display Session Data in Views
To display session data in views, you can simply echo the variable that was passed to the view. For example, in the header view:
Welcome, <?php echo $username; ?>
Conclusion
That’s it, you learned how to set and retrieve session data in controllers and views.