Welcome Guest, Not a member yet? Register   Sign In
Accessing CI session data within a view
#1

[eluser]mortifrog[/eluser]
Is it possible to access CI session data inside of a view?

I get the following error

'Using $this when not in object context' when trying: $this->session->set_userdata('blah', $blah);

Before you rush to tell me I'm breaking protocol and should only do this inside a controller - I know, but I have a good reason for wanting use this code inside a view and wondered if there's a way round? I have autoloaded session in autoload.php - Is there something I can instantiate to be able to access my session data in a view?
#2

[eluser]Colin Williams[/eluser]
Actually, there's a way to do this anywhere: the get_instance() function.

Code:
<?php $ci =& get_instance(); ?>
<div>
   &lt;?php print $ci->session->userdata('username') ?&gt;
</div>

Not sure what "protocol" it is you would be breaking, but it still seems like a bad idea. Imagine someone else comes to modify the app, or you do later. Is it intuitive to look in a View to see where and how certain session data is set?
#3

[eluser]mortifrog[/eluser]
I'm trying to implement my own captcha script which relies on session variables. I have already got the script working in a non framework environment. I'm gonna have to sleep on this I think. Could I put the captcha code in a controller and load that controller through an image tag I wonder?

btw - I tried $ci =& get_instance(); in a view but got the folowing error:

Call to undefined function: get_instance()
#4

[eluser]KPowell[/eluser]
That's because the view variables are separate from all other variables. Another way you could do it is to pass the session (or whichever variables you need) as a variable to the view, then access it from there. So, in your controller, it'd be something like:

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

Then, in the view, you could access everything from the $userdata variable.

Personally, whatever it is doing, I would throw that into a controller and pass whatever you need (sounds like an image in this case) as a variable to the view, rather than having the view process anything. That way, all the processing is happening outside of the view.
#5

[eluser]mortifrog[/eluser]
That doesn't look like it should work for passing session variables to a view - but I'll take your word for it that it does. I don't think it helps though me though. When I have a few minutes, I'm going try what I said before - ie loading the captcha as a controller through an image tag situated in a view.
#6

[eluser]mortifrog[/eluser]
Yes I understand now thank you. That is the way I have done it and shall do from now in :-) I realised I didn't have any need for the variables in the view at all. Just called the controller from an image tag in the view. All processing done in the controller.




Theme © iAndrew 2016 - Forum software by © MyBB