Skip to content
CODE THE PIXEL
CakePHP

CakePHP 4 Create, Write and Read Session Data

Asyraf Wahi Anuar 2 min read

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:

PHP
$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
<?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.

Leave a comment

Markdown works: `code`, ``` blocks, **bold**, links.

First comments are reviewed before they appear.

CakePHP

Using Bahasa Melayu Table Names in CakePHP

Learn how to use Bahasa Melayu table names like "pengguna" in CakePHP while following the framework’s naming conventions. Includes tips for using the Bake tool and avoiding pluralization issues.

5 min read

Tools & Software

Formatting PHP in VSCode Using Prettier and PHP Intelephense

Learn how to set up Visual Studio Code (VSCode) for automatic PHP file formatting using the Prettier and PHP Intelephense extensions. This step-by-step tutorial will help you maintain a clean and organised codebase, enhancing your PHP development experience.

2 min read