CakePHP 4 Create, Write and Read Session Data
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.
This tutorial may be outdated
It was last reviewed 4 years ago. Some steps may differ in newer versions.
Tech stack
- CakePHP 4.x
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 sessionRead 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 :)
Did this tutorial help?
264 readers found this helpful
Comments
No comments yet. Questions about this tutorial are welcome here: the answer helps the next reader too.