Step-by-Step Pack

Zend Framework Session Step by Step Tutorial

Manage sessions in Zend Framework using Zend_Session. Covers namespaces, data access, locking, unlocking, viewing namespace values, and automatic expiration.

Zend Framework session management

Why Zend_Session?

PHP has built-in session support through $_SESSION, and it works fine for simple cases. But as applications grow, you run into problems. Multiple components write to $_SESSION and stomp on each other’s keys. There is no way to expire individual values. Locking behavior is all-or-nothing.

Zend_Session_Namespace solves these problems. It partitions the session into named namespaces so different parts of your application get isolated storage. It adds per-variable expiration. And it provides locking to prevent accidental overwrites.

Pack Overview

Six articles take you through the full Zend_Session feature set. They are designed to be read in order, starting with the introduction and building up through namespaces, data access patterns, inspection, locking, and expiration.

Walkthrough

Step 1 - Session Introduction

The first article covers how Zend_Session wraps PHP’s native session handling. You start a session with:

1
Zend_Session::start();

Or it starts automatically when you create your first namespace. The important thing is that Zend_Session manages the session_start() call for you, including configuration options like cookie parameters and save handlers.

Step 2 - Using Namespaces

A namespace is just a named partition:

1
2
3
4
5
6
$userSession = new Zend_Session_Namespace('user');
$userSession->name = 'Jamie';
$userSession->role = 'admin';

$cartSession = new Zend_Session_Namespace('cart');
$cartSession->items = array();

The user and cart namespaces are completely separate. Changing a value in one does not affect the other. This is the main advantage over raw $_SESSION.

Under the hood, namespaces use $_SESSION['user'] and $_SESSION['cart'] as storage. But you interact with them through the object API, which is cleaner and supports additional features.

Step 3 - Accessing Session Data

Reading data back is straightforward:

1
2
$userSession = new Zend_Session_Namespace('user');
echo $userSession->name; // Jamie

You can create a new Zend_Session_Namespace object with the same name anywhere in your code and it accesses the same data. The namespace name is the key, not the PHP variable.

The accessing session data article covers iteration, checking if a value exists with isset(), and removing values with unset().

Step 4 - Inspect Namespace Values

Sometimes you need to see everything stored in a namespace for debugging. The fourth article shows how to iterate over all values:

1
2
3
4
$session = new Zend_Session_Namespace('user');
foreach ($session as $key => $value) {
echo "$key: $value\n";
}

This is useful when diagnosing unexpected behavior. You can dump the namespace contents to a log file or debug output.

Step 5 - Lock and Unlock Namespaces

Locking prevents writes to a namespace:

1
2
3
4
5
6
7
8
$session = new Zend_Session_Namespace('config');
$session->lock();

// This throws an exception:
$session->newValue = 'test';

$session->unlock();
// Now writes work again

Locking is useful for config-like session data that should not change after initialization. It catches accidental writes that could cause subtle bugs.

You can check lock status with $session->isLocked().

Step 6 - Automatic Expiration

The expiration article covers two types of automatic cleanup:

Hop-based expiration removes a value after a set number of requests:

1
$session->setExpirationHops(3, 'flashMessage');

After three page loads, flashMessage disappears. This is perfect for one-time notifications.

Time-based expiration removes values after a number of seconds:

1
$session->setExpirationSeconds(300, 'tempToken');

The tempToken value expires after five minutes. Useful for CSRF tokens, temporary download links, or verification codes.

You can set expiration on the entire namespace or on individual keys.

Common Pitfalls

Calling session_start() manually. If you call session_start() before Zend_Session::start(), you get a warning. Let Zend_Session manage the lifecycle.

Using $_SESSION directly alongside Zend_Session. They access the same underlying data. If you write to $_SESSION['user']['name'] directly, the namespace object may not reflect the change correctly. Pick one approach and stick with it.

Not configuring session save path. On shared hosting, the default /tmp directory may be shared or have restrictive permissions. Set a custom save path in your config.

Storing large objects in the session. Sessions are serialized to disk on every request. Storing large arrays or objects slows down every page load. Keep session data small - IDs, flags, and short strings.

FAQ

Can I use database-backed sessions?
Yes. Zend_Session supports custom save handlers. Use Zend_Session_SaveHandler_DbTable to store sessions in a database table. This is essential for load-balanced setups where multiple servers need to share session data.

How do I destroy a session completely?
Call Zend_Session::destroy(). This removes all session data and invalidates the session cookie. Use it for logout or account deletion flows.

What is the difference between Zend_Session and Zend_Auth?
Zend_Session manages raw session data. Zend_Auth is specifically for authentication identity. Under the hood, Zend_Auth stores its data in a Zend_Session_Namespace called “Zend_Auth”.

How do I handle session expiration gracefully?
Check Zend_Auth::getInstance()->hasIdentity() at the start of protected actions. If the session expired, redirect to the login page with a message explaining what happened.

Can I change the session cookie name?
Yes. Call Zend_Session::setOptions(array('name' => 'MYAPPSESSID')) before the session starts. This is a good practice for avoiding cookie collisions when multiple applications run on the same domain.

Articles in This Pack

  1. 1 Zend Framework Session - Introduction
  2. 2 Zend Framework Session - Using Namespace
  3. 3 Zend Framework Session - Accessing Session Data
  4. 4 Zend Framework Session - Seeing All Values at Namespace
  5. 5 Zend Framework Session - Locking and Unlocking Namespace
  6. 6 Zend Framework Session - Automatic Expiration

Pack Checklist

  • PHP with session support enabled
  • A running Zend Framework project
  • Session save path writable by the web server
  • Understanding of HTTP statelessness and why sessions exist
  • Zend_Session component available in the library