views:

899

answers:

3

hi i have a varible contaning "username" and want to get these values via session to any of the view page. How can i use session vaible in view

A: 

If you're in the controller, use the Session component. It's included, by default, in all the controllers. It has the Session::read() and Session::write() methods. Check out http://book.cakephp.org/view/173/Sessions for more information.

I believe, if the Session component is like some of the other components, you can use it inside the views. Try just doing $session->read() in your view code blocks. If that doesn't work, try doing a $this->Session->read(...). As a last resort, if none of those work, you can always use the good old PHP $_SESSION, although it's kinda veering outside the Cake framework. However, if you are sure you're not going to use Cake's Session management (and you don't really have to, IMO, as it's little more than a wrapper around $_SESSION), then just know when to properly apply the hack.

Travis Leleu
The Cake Session management *is* more than just a wrapper around `$_SESSION`, as it supports several more backends for storing session data. You can choose to write the session to a database to potentially share it across servers without having to change a single instance of `$this->Session->write()` in your app.
deceze
True, although I think I would use a different method within php to change the other session handlers, rather than putting it inside Cake. Guess you caught me thinking mostly of how I think of the component, for how I would use it.
Travis Leleu
It's already there and it works fine, why not use it? :-)
deceze
+2  A: 

There's a SessionComponent available in your Controller that you can use like $this->Session->write('Name', 'Value');. Analogously there's also the SessionHelper for the View, which does very similar things and can be used like $session->read('Name');.

deceze
A: 

can i use this $this->Session->write('Name', 'Value'); is in ctp(view) file

Gaurav Mahehswari