Reputation: 335
I'm reading the Codeigniter 2.2 tutorial and I am not clear on how to use sessions for logging in.
Say I have a login.php, which checks user data with the database. Then if its ok then I should set the session in a controller?
$this->load->library('session');
And then in say admin.php page I should check if session exists by? :
$this->session->user_data('item'); ??
Or how do I check if the person is logged in?
Thank you
Upvotes: 6
Views: 91928
Reputation: 1131
$this->load->library('session'); // load the session library
$this->session->userdata("email") // check for the variable "email" in session array
Upvotes: 0
Reputation: 662
Based on the docs, to do anything custom within session you need to load the session library. If you plan to use session throughout your application, I would recommend autoloading the library. You do this from within config/autoload.php.
$autoload['libraries'] = array('session');
Then you won't have to use $this->load->library('session');
on every page.
After the library is loaded, set your custom information, maybe based off some information from your database. So in your case, this would be in login.php:
$this->session->set_userdata('userId', 'myId');
where userId
would be the name of the session variable, and myId
would be the value.
Then, on subsequent pages (admin.php), you could check that the value is there.
if($this->session->userdata('userId') == '') { //take them back to signin }
Upvotes: 13
Reputation: 1131
load session library
$this->load->library('session');
set session
$_SESSION['email'] = $data['email'];
unset session
$this->session->unset_userdata($_SESSION['email']); // $this->session->sess_destroy();
Upvotes: 4
Reputation: 399
To set user session
$the_session = array("key1" => "value1", "key2" => "value2");
$this -> session -> set_userdata($the_session);
To read user session
$foo = $this -> session -> userdata('key1');
You need $this->load->library('session');
every time prior you use CI session functions. Or you can set it up in autoload.php $autoload['libraries'] = array('session');
Upvotes: 3