In Set and Display Session Data in CodeIgniter, first we have to learn a little bit about Session in CodeIgniter.
When we develop a website, we need to track user’s state and activity for this we have to use Session. In CodeIgniter session library or class already available to use. We just initialize it on our program.
CodeIgniter Session Initialization
Session in CI, session data are globally available through the complete website, if we want to get those data we have to first initialize the session first.
1 2 |
$this->load->library('session'); |
Set Session Data in CodeIgniter
After initialize the session we can set the user’s data. Here are 2 types of setting methods,
- Set Single Data in CodeIgniter Session
- Set Multiple Data in CodeIgniter Session
Set Single Data in CodeIgniter Session
For setting one value we use the $this->session
session object and set_userdata
function which accepts 2 parameters.
1 2 |
$this->session->set_userdata('any_name', 'their_value'); |
Set Multiple Data in CodeIgniter Session
For setting up the multiple data in session we use the same set_userdata
function which can also support array values.
1 2 3 4 5 6 7 |
$newdata = array( 'username' => 'johndoe', 'email' => 'johndoe@some-site.com', 'logged_in' => TRUE ); $this->session->set_userdata($newdata); |
Display Session Data in CodeIgniter
Here are 2 types of displaying session data in CI,
- Show specific data from the session.
- Show all data from the session.
Show Specific Data From CodeIgniter Session
For showing specific data we use the key name of the session data. Here is the complete example to Display Session Data in CodeIgniter,
Example:
1 2 3 4 5 6 7 8 |
$username = 'PHP Coder'; //setting data $this->session->set_userdata('username',$username); //display the data from session $var = $this->session->userdata; echo $var['username']; |
Show All Data From Session
For showing complete data from the session we use all_userdata()
function to get complete data in array format.
Example:
1 2 |
echo '<pre>'; print_r($this->session->all_userdata()); |
Here are the complete solution to set and display session data in CodeIgniter.
If you want to know more about the session you can go to the official documentation of CodeIgniter, https://codeigniter.com/userguide3/libraries/sessions.html
Also Check:
- Auto Add Country Code in Input using JavaScript
- jQuery Contact Form Send Email Using Ajax
- How to Store Data In Cookies Using JavaScript
- Login with Google Account using PHP Step by Step
Happy Coding..!
Hi I have a query,
I am doing a Ajax call which direct to PHP class and sets userData there and after that is return the data to js , if data is success it redirects to other controller where session i.e $this->session->userdata gets destroyed.
what could be the reason behind this ?
thanks
Please refer this link https://stackoverflow.com/questions/25459807/session-destroying-in-codeigniter-after-redirecting