Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

CakePHP Session variable use in view page?

I have a variable contaning "username" and want to get these values via session to any of the view pages.

How can I get this session variable in the view ?

like image 313
coderex Avatar asked Oct 20 '09 20:10

coderex


People also ask

How can I use session in cakephp 4?

A basic example of session usage in controllers, views and cells would be: $name = $this->request->getSession()->read('User.name'); // If you are accessing the session multiple times, // you will probably want a local variable. $session = $this->request->getSession(); $name = $session->read('User.name');

How are session variables used?

Session variables are special variables that exist only while the user's session with your application is active. Session variables are specific to each visitor to your site. They are used to store user-specific information that needs to be accessed by multiple pages in a web application.

Why session variables are used in PHP?

Session variables solve this problem by storing user information to be used across multiple pages (e.g. username, favorite color, etc). By default, session variables last until the user closes the browser. So; Session variables hold information about one single user, and are available to all pages in one application.


3 Answers

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');.

like image 175
deceze Avatar answered Oct 08 '22 18:10

deceze


You can use $this->Session->read('myParam') in your Views files.
But you can't use $this->Session->write('myParam').

As noted here:

The major difference between the Session Helper and the Session Component is that the helper does not have the ability to write to the session.

like image 36
trante Avatar answered Oct 08 '22 18:10

trante


To use it in a helper you must remember to include it in your $helpers declaration:

class Foo extends AppHelper
{
    var $helpers = array('Session','Bar');
like image 26
Andy Avatar answered Oct 08 '22 17:10

Andy