Code The Pixel

CakePHP 4 Create, Write and Read Session Data

Asyraf Wahi Anuar - November 27, 2021
Published in CakePHP 2713 Views Email This Article
Estimated reading time: 48 seconds

On top of PHP's native session extension, CakePHP adds a wrapper and a suite of utility functions. Sessions enable you to identify and keep persistent data for individual users while identifying unique users across requests. Session data, unlike cookies, is not accessible on the client-side. CakePHP makes it simple to create a custom session handler. In this example, we'll write a session handler that saves sessions to the Cache.

Write Data To Session
You can write data into a session from the controller. The following code writes the session 'name' which the value is requested from the 'name' input:

$session = $this->getRequest()->getSession(); //get session
$session->write('name', $this->request->getData('name')); //write name value to session


Read Data From Session
To read and print the session data, use the following code in a view:

<?php 
$session = $this->request->getSession(); //read session data
echo $session->read('name');
?>


That's all. Happy coding :)


Cite this article (APA 6th Edition)