How to set session in Codeigniter after login?

by darrion.kuhn , in category: PHP Frameworks , 8 months ago

How to set session in Codeigniter after login?

Facebook Twitter LinkedIn Telegram Whatsapp

1 answer

by giovanny.lueilwitz , 3 months ago

@darrion.kuhn 

In Codeigniter, you can use the $this->session->set_userdata() method to set session data after a user logs in. Here's an example of how you can use it:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
// Load the session library
$this->load->library('session');

// Set session data
$newdata = array(
   'username'  => 'johndoe',
   'email'     => 'johndoe@example.com',
   'logged_in' => TRUE
);

$this->session->set_userdata($newdata);


This will create a new session with the given data. You can then use the $this->session->userdata('key') method to retrieve the value of a particular session variable. For example, to retrieve the username, you can use $this->session->userdata('username').


You can also use the $this->session->set_flashdata() method to set temporary session data that will be available only for the next server request, and will be automatically deleted afterwards.

1
$this->session->set_flashdata('message', 'You have successfully logged in');


This can be useful for displaying success or error messages to the user after a form submission. You can retrieve flash data using the $this->session->flashdata('key') method.

1
echo $this->session->flashdata('message');