Zend Framework - Session Management

A Session is a very important concept in a web application. It provides the option to persist the user's data in the web server for a limited period of time. Zend framework provides a separate component, zend-session to handle the session information.

Install a Session Component

Session component can be installed using the Composer as specified below −

composer require zendframework/zend-session 

Session Components

Zend framework provides six components to handle session management. All these components have been explained below −

  • Zend\Session\Container − The main API to read and write the session information.

  • Zend\Session\SessionManager − It is used to manage the entire lifecycle of a session.

  • Zend\Session\Storage − This is used to specify how the session data will be stored in the memory.

  • Zend\Session\SaveHandler − It is used to store and retrieve the session data into a physical location like RDBMS, Redis, MangoDB, etc.

  • Zend\Session\Validator − This is used to protect session from hijacking by cross-checking initial and subsequent request's remote address and user agent.

  • Zend\Session\Config\SessionConfig − It is used to configure how the session should behave.

The default configuration is enough to work with a session. Using the above components, all aspects of a session can be handled easily.

Session Component Example

Let us adhere to the following points to create a new page to understand a session in Zend framework. By default, it is enough to create an instance of a Container class to manage sessions.

  • Create a new action, sessionAction in TutorialController.

  • Initialize a Container object.

$c = new Container();
  • Check whether an arbitrary key count exists. If the key is not available, initialize the count with value 1. If it is available, increment the value as shown in the following code.

if (!isset($c->count)) { 
   $c->count = 0; 
} else { 
  • Register the count in the ViewModel.

  • Create a template file for – sessionAction, session.phtml in myapp/module/Tutorial/view/tutorial/tutorial/session.phtml and then render the count value.

  • Refreshing the page will increase the value of count in the session. The complete listing is as follows −


public function sessionAction() { 
   $c = new Container();  
   if (!isset($c->count)) { 
      $c->count = 0; 
   } else { 
   $view = new ViewModel([ 
      'count' => $c->count, 
   return $view; 


Session data, COUNT = <?= $this->count ?>

Sample Result

Session data, Count = 5
Kickstart Your Career

Get certified by completing the course

Get Started