March 12, 2012

SESSION missing from view

Question by KYSH

as per title above, when I trigger the controller with a hyperlink, it does runs the controller function but I couldn’t get the value of SESSION after redirect from controller. The code is as follows…

function langpref($lang){       
    $this->load->helper('url');
    redirect(ABSOLUTE_PATH, 'location');        

    $this->session->set_userdata('cur_lang', 'xxx');        
}   

*Note: ABSOLUTE_PATH is a constant of the hyperlink, and I already load the SESSION library in the autoload file.

In my view file, I written the code as follows…

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

and it doesn’t print out the SESSION value.

Answer by Starx

First Approach: You cannot access session variables like that

<?php $ci =& get_instance(); ?>
<div>
   <?php echo $ci->session->userdata('cur_lang') ?>
</div>  

Second Approach: Another way you can do this is pass the session data to the view

On your controller

$data['userdata'] = $this->session->userdata;
$this->load->view('your/view', $data); 

On your view

echo $userdata['cur_lang'];

Author: Nabin Nepal (Starx)

Hello, I am Nabin Nepal and you can call me Starx. This is my blog where write about my life and my involvements. I am a Software Developer, A Cyclist and a Realist. I hope you will find my blog interesting. Follow me on Google+

...

Please fill the form - I will response as fast as I can!