Using Sessions In Zend Framework 2 - Part 1

We all know that PHP implements a stateless approach to applications. The PHP process starts, variables are allocated, information generated and stored, then when the request is finished, all of the state is lost. Any information generated and stored during the request, during its lifetime, is lost when it ends.

To help work around this, PHP introduced the concept of sessions, which allows for storing information across requests. However, like most things, as application's have become more complex, the ability to interact with sessions in a way that matches the needs of the application has continued to grow as well.

Gladly, in Zend Framework 2, a set of classes is available, which helps reduce the complexity of managing session information, whether that's interaction, configuration or backend storage, without placing too much distance between you and the underlying PHP implementation, or adding too much complexity in the process.

In today's article, the first in a two-part series looking at using sessions in Zend Framework 2, we're going to show how to get a basic configuration up and running, so that you can start working with them today, in your ZF2-based apps.

For the purposes of today's tutorial, I'll assume that you've implemented a basic project using the ZF2Skeleton repository, and that it's up and running, but that you've not gone too much further. If you have though, that's perfectly fine.

We'll extend the default Application module, to provide session support to the rest of the application. To integrate session support, we only need to do 4 things:

  1. Update Module.php
  2. Create a New Container & Store Some Data
  3. Retrieve The Data

Let's step through each of these now.

1. Update Module.php

Firstly, in module/Application/Module.php, we need to do three things:

  • Add in two use statements
  • Create a new function, which initialises the session
  • Call the function in onBoostrap

So first, add in the following two use statements:

use Zend\Session\Config\SessionConfig;
use Zend\Session\Container;

Then, add in the following function.

public function initSession($config)
    $sessionConfig = new SessionConfig();
    $sessionManager = new SessionManager($sessionConfig);

initSession creates a new SessionConfig variable, which provides the configuration settings for the session manager. We then set a few options, on it and pass it as the sole argument, when instantiating a new SessionManager. Finally, we call the static setDefaultManager method on the Container class, passing in the new $sessionManager variable.

Let's look at that a bit more closely.

  • Container: The provides the core interface for managing session data.
  • SessionConfig: Handles setting various session config options.
  • SessionManager: Handles session management, such as session start / exists / write / regenerate id / time to live / and destroy, as well as session validation.

In onBootstrap, add the following:

    'remember_me_seconds' => 180,
    'use_cookies' => true,
    'cookie_httponly' => true,

This will ensure that the Session is always setup and ready to go. With this code in place, we now have session support available, using cookies to store the session information, persisting them after the browser closes for 3 minutes.

2. Create a New Container & Store Some Data

$sessionTimer = new Container('timer');
// Could also use offsetSet('executionTime', (float) array_sum(explode(' ', microtime())));
$sessionTimer->executionTime = (float) array_sum(explode(' ', microtime()));

Ok, now that the we've taken care of the setup, we now need to make use of it and store information in it. So now, we create a new session object container, called timer and in there, store the current value of microtime() in a container variable, called executionTime.

Containers are a way of namespacing the session information. A default namespace is available, but I think in all but the simplest of applications, this may not be the most effective approach. So, by being able to segregate the information, it makes it easier to consider it semantically and programmatically.

3. Retrieve The Data

Right, now that the information's stored, let's go about retrieving and using it. So, at some other point in our application, I'll assume a controller action, let's do that.

$sessionTimer = new Container('timer');
// Could also use offsetGet('executionTime');
if ($sessionTimer->executionTime) {
    return sprintf(
      "Page rendered in %s seconds.",

Here, as with when setting the information, we make use of a Container object. Whereas in the first example, when the container wouldn't have existed and would have been created, now that it exists, we'll now get access to the existing container.

Now, like most variables, we can interact with it, checking if the property we're looking for, executionTime, is available. If so, we then using the sprintf function to display the information, nicely formatted.

Wrapping Up

So there you have it. With only a little bit more work, we now have access to Sessions in a ZF2-way, yet with an added level of sophistication, whether that's the backend where the information's stored, the implementation of session namespaces or the level of configuration options available. It's a really nice library that makes interacting with Sessions quite a breeze.

In next week's tutorial, we'll build on today's by seeing how to protect sessions against session hijacking by making use of the available validators, as well as how to make use of different storage backends, such as cache servers, and databases.

About Matthew

Matthew Setter Matthew Setter is a PHP & Zend Framework specialist. If you're in need of a custom software application, need to migrate an existing legacy application, or want to know your current application's GPA - get in touch.