如何使用不同的codeigniter方法访问会话?

I'm new to codeigniter. How do i use session objects to pass value from one method to another method in controller?

I've loaded the library in my constructor class:

$this->load->library('session');

1st function:

public function display()
{
$data = array(
'word' => 'hello'
);
$this->session->set_userdata($data);
}

2nd function:

public function validate()
{
$word_generated = $this->session->userdata('word');
}

But i'm not able to access the session value in the second method.

The code works fine if i access the session within the same method:

public function display()
{
$data = array(
'word' => 'hello'
);
$this->session->set_userdata($data);
$word_generated = $this->session->userdata('word');
}

Y am i not able to access it in second method then? Please guide.. Thanks a lot

In order to access the session data from method to method (or page-to-page), you should do a redirect.

For instance:

public function display() {
    $data = array(
        'word' => 'hello'
    );
    $this->session->set_userdata($data);
    redirect('your_controller/validate');
 }

 public function validate() {
     $word_generated = $this->session->userdata('word');
 }

If you're simply trying to share a variable with two methods in the same controller on the same call, you have two options:

1. Set a public property for you controller class:

class Your_controller extends CI_Controller {
    public $word;
    public function display() {
       $this->word = 'hello';
       $this->validate();
    }

    public function validate() {
       $word_generated = $this->word;
    }
}

2. Just pass the variable to the method normally:

class Your_controller extends CI_Controller {
    public $word;
    public function display() {
       $this->validate('hello');
    }

    public function validate($word='') {
       $word_generated = $word;
    }
}

Hope that helps you.

Using CI 1.7.x, I found an error in my webapp where it just stopped reading my session_data. What I did to correct this was change the $config['sess_encrypt_cookie'] in config.php to TRUE; and it started working again. Of course, in the log files a cookie corruption error kept popping up...

Hope it helps