CakePHP 4 Custom Session Handler To Access Session

Reading Time: 6 minutes
2,730 Views

Inside this article we will see the concept of CakePHP 4 Custom Session Handler To Access Session. By the help of this concept you will get the complete access over sessions in many like for read, write, etc operations.

This tutorial will give you the classified information about creating and handling custom sessions. You can access the session data at any place by using a request object. We can create custom session handler by request object for values at Controller, Views, Helpers, etc.

A session is a way to store information (in variables) to be used across multiple pages. Unlike a cookie, the information is not stored on the users computer.

Learn More –

Let’s get started.

CakePHP 4 Installation

To create a CakePHP project, run this command into your shell or terminal. Make sure composer should be installed in your system.

$ composer create-project --prefer-dist cakephp/app:~4.0 mycakephp

Above command will creates a project with the name called mycakephp.

Custom Session Handler

We create custom session handler (it’s an object) by using request object. By using session object we can do all operations Read, Write, Delete, etc.

Create Session Object

First we need to create an instance of session handler for all operations.

$this->session = $this->request->getSession();

Write Session Key Value

To write session key value pairs we use write() method of $session object.

// Save a single key value
$this->session->write("name", "Sanjay Kumar");

// Save array values to a key
$this->session->write("user", [
    "username" => "sanjay_owt",
    "designation" => "developer",
    "email" => "sanjaytest@gmail.com"
]);

// Create multiple keys
$this->session->write([
    "player_name" => "Suresh Raina",
    "age" => "36",
    "team" => "CSK"
]);

Read Session Key Value

To read session key value we use read() method of $session object.

$this->session->read("name");

$this->session->read("user");

Check Session Key Exists

To check session key existence we use check() method of $session object.

if ($this->session->check("name")) {
    echo "Session key exists";
} else {
    echo "Session key doesn't exists";
}

Delete a Single Session Key

To delete a specific session key we use delete() method of $session object.

if ($this->session->check("name")) {
    // It will delete the session key "name"
    $this->session->delete("name");
}

Destroy All Session Keys

To delete all session keys we use destroy() method of $session object.

// It will remove all the session keys
$this->session->destroy();

Let’s see all operations by using it in application.

Create Controller

Open project terminal and this bake console command to create controller class.

$ bin/cake bake controller Site --no-actions

It will create a controller class SiteController.php inside /src/Controller folder. Open and write this following code into it.

<?php

declare(strict_types=1);

namespace App\Controller;

class SiteController extends AppController
{
    private $session;

    public function initialize(): void
    {
        parent::initialize();
        $this->session = $this->request->getSession();

        $this->autoRender = false;
    }

    public function writeSession()
    {
        // Save a single key value
        $this->session->write("name", "Sanjay Kumar");

        // Save array values to a key
        $this->session->write("user", [
            "username" => "sanjay_owt",
            "designation" => "developer",
            "email" => "sanjaytest@gmail.com"
        ]);

        // Create multiple keys
        $this->session->write([
            "player_name" => "Suresh Raina",
            "age" => "36",
            "team" => "CSK"
        ]);
    }

    public function readSession()
    {
        echo $this->session->read("name");

        echo "<br/>";

        print_r($this->session->read("user"));

        echo "<br/>";

        echo $this->session->read("player_name");
    }

    public function checkSession()
    {
        if ($this->session->check("name")) {
            echo "Session key exists";
        } else {
            echo "Session key doesn't exists";
        }
    }

    public function deleteSession()
    {
        if ($this->session->check("name")) {
            // It will delete the session key "name"
            $this->session->delete("name");
        }
    }

    public function removeSession()
    {
        // It will remove all the session keys
        $this->session->destroy();
    }
}

You can see we have all the methods of Write, Read & Delete session key values by using session object.

Next,

We will bind all these methods to application routes.

Create Route

Open routes.php file from /config folder. Add this route into it.

//...

// sessions
$routes->connect(
    '/write-session',
    ['controller' => 'Site', 'action' => 'writeSession']
);

$routes->connect(
    '/read-session',
    ['controller' => 'Site', 'action' => 'readSession']
);

$routes->connect(
    '/check-session',
    ['controller' => 'Site', 'action' => 'checkSession']
);

$routes->connect(
    '/delete-session',
    ['controller' => 'Site', 'action' => 'deleteSession']
);

$routes->connect(
    '/remove-session',
    ['controller' => 'Site', 'action' => 'removeSession']
);

//...

Application Testing

To execute start development server.

$ bin/cake server
  • Write Session – http://localhost:8765/write-session
  • Read Session – http://localhost:8765/read-session
  • Check Session Existence – http://localhost:8765/check-session
  • Delete a Specific Session Key – http://localhost:8765/delete-session
  • Remove All Session Keys – http://localhost:8765/remove-session

We hope this article helped you to learn CakePHP 4 Custom Session Handler To Access Session Tutorial in a very detailed way.

Online Web Tutor invites you to try Skillshike! Learn CakePHP, Laravel, CodeIgniter, Node Js, MySQL, Authentication, RESTful Web Services, etc into a depth level. Master the Coding Skills to Become an Expert in PHP Web Development. So, Search your favourite course and enroll now.

If you liked this article, then please subscribe to our YouTube Channel for PHP & it’s framework, WordPress, Node Js video tutorials. You can also find us on Twitter and Facebook.