• 0
Votes
name
name Punditsdkoslkdosdkoskdo

Where to set session in php Codeigniter?

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?

name
  • 1
Teacher

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 }

  • 1
Reply Report