</> Code The Pixel

CakePHP 4 Create, Write and Read Session Data

Asyraf Wahi Anuar - November 27, 2021

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:

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

That's all. Happy coding :)

Cite this article (APA 6th Edition)

CakePHP 4 Print PDF Using CakePDF
May, 17 2020
CakePHP 4 Authentication Using Auth...
May, 14 2020
CakePHP 4 jQuery Date Time Picker
October, 01 2018
CakePHP 4 Export To CSV
May, 29 2020
CakePHP 4 Authentication Using...
May, 11 2020
CakePHP 4 File Upload Using Proffer Plugin
May, 15 2020
CakePHP 4 Find, Sort & Count
June, 02 2020
Sharing Link
Click the icon to share