0
votes

I'm new to CodeIgniter and I started to use the session library.

I have autoloaded the session library and trying to save the current user_id to the session userdata array. But the information is gone when I try to read it on an other page..

The native PHP sessions work just fine (tested it), so it must be something from CI.

I programmed a simple test page where I test the following:

  • Set the session userdata.
  • Test page shows the userdata correctly.
  • Uncomment the set session data lines in the code of the controller and reload the page.
  • Test page doesn't show the userdata.

The code of the controller:

class Welcome extends CI_Controller {

   public function index(){ 
        $data = null;

        $data['test'] = "Yeeeeh!!";
        $this->session->set_userdata($data);

        $this->load->view('welcome_message', $data);
    }
}

Code of the view:

<?php
    echo $this->session->userdata('test');
?>
2
Please read the manual how the session helper works, before you ask questions. See here: codeigniter.com/user_guide/libraries/sessions.html - hakre
Thx for the clear comment... I read the manual and did all the things it stated. I autoloaded the library, setted the session vdata and then try to read it.. - Sven van Zoelen
So if you don't get any errors, you installed it OK. Now read the manual again, but this time about how to use it. Especially the part about how to name a session value. - hakre
I made a typing error in stackoverflow.. If you read the bullit list then in step 2 you'll read that the output is successfull.. And in step 4 not! - Sven van Zoelen
Okay the next step is to understand what a view is and how you pass variables into a view. See codeigniter.com/user_guide/general/views.html - hakre

2 Answers

0
votes

Why does the view display the session_id and not the "test" variable you created?

Did you test

<?php
echo $this->session->userdata('test');

?>

in the view file?

-1
votes

CI's sessions are cookies, not PHP native sessions. Calling sessions in a view works (IIRC), but since your view is loaded in the same request the session is created, it won't be set.

You need to call it on another request (i.e. another controller), or set the session somewhere else (in another controller, via AJAX could work also), or use native PHP $_SESSION array instead.

I think your actual code is just a test case, otherwise why not just

public function index(){ 
        $data = null;

        $data['test'] = "Yeeeeh!!";
        $this->session->set_userdata($data);

        $this->load->view('welcome_message', $data);
    }

in view:

<?php
  echo $test;
?>