How do I create, write, and read session data in CakePHP?

The bakery is your best friend:

http://book.cakephp.org/view/398/Methods

All your session read/writes belong in the controller:

$this->Session->write('Person.eyeColor', 'Green');

echo $this->Session->read('Person.eyeColor'); // Green

In cake php you can create session like this

$this->request->session()->write('user_id', 10);

and you can read session value like this

echo $this->request->session()->read('user_id');

Super Simple!


You don't have to write any code to create session, they are already built in. Then you just use the read and write sessions as mentioned above. Also see here for more details:

http://book.cakephp.org/2.0/en/core-libraries/components/sessions.html Used in Controllers

http://book.cakephp.org/2.0/en/core-libraries/helpers/session.html Used in Views


cakephp 4 example of session usage in controllers, views and cells

$session = $this->request->getSession();
$session->write('abc', 'apple');
echo $session->read('abc');