Usage Guide

Starting a session

Create a Session instance and call start() to initialize the session:

use Vespula\Session\Session;

$session = new Session();
$session->start();

Starting the session is explicit rather than automatic. This allows you to configure the session before PHP starts it.

Calling start() more than once on the same Session instance has no effect.

If a PHP session has already been started elsewhere in the application, Vespula Session will adopt the existing session rather than attempting to start another one. In this situation, options passed to start() cannot change PHP’s existing session configuration.

For most applications, create and start the session early in the application’s bootstrap process, before other components need to access session data.

Configuration

Vespula Session provides several methods for configuring PHP session behaviour. These should generally be called before start().

Session options

The start() method accepts an optional array of PHP session options:

$session->start([
    'cookie_secure' => true,
    'cookie_samesite' => 'Lax',
]);

These options are merged with the library’s defaults. Any supplied options override the corresponding defaults.

The library currently uses the following defaults:

Option

Default

Description

use_strict_mode

1

Enables strict session ID handling.

cookie_httponly

1

Prevents JavaScript from accessing the session cookie.

cookie_samesite

Strict

Sets the cookie’s SameSite policy.

cookie_lifetime

0

Keeps the cookie until the browser session ends.

use_cookies

1

Uses cookies to store the session ID.

use_only_cookies

1

Prevents session IDs from being passed through URLs.

use_trans_sid

0

Disables transparent session ID propagation.

cache_limiter

nocache

Sets the session cache limiter.

For production applications using HTTPS, consider enabling the cookie_secure option:

$session->start([
    'cookie_secure' => true,
]);

This ensures that the browser only sends the session cookie over secure connections.

Refer to the PHP session configuration documentation for the complete list of available session options.

Setting the session name

Use setName() to change the PHP session name:

$session->setName('MYAPP_SESSION');
$session->start();

The session name must be set before the session starts.

Setting the idle timeout

Vespula Session provides its own idle timeout, which determines how long session data can remain inactive before the library considers it expired.

Use setMaxIdle() to configure the timeout in seconds:

$session->setMaxIdle(1800);
$session->start();

The default idle timeout is based on PHP’s session.gc_maxlifetime setting.

The configured idle timeout cannot exceed PHP’s session.gc_maxlifetime. This helps avoid setting an application timeout longer than the configured lifetime of the underlying session storage.

When the idle timeout is exceeded, the library clears its session container, including all segments. The underlying PHP session remains active, but the application should treat the previous session data as expired.

You can retrieve the configured timeout using:

$maxIdle = $session->getMaxIdle();

Custom session save handlers

Vespula Session supports custom PHP session save handlers through setSaveHandler().

The handler must implement PHP’s SessionHandlerInterface:

$handler = new MySessionHandler($pdo);

$session->setSaveHandler($handler);
$session->start();

The save handler must be registered before the PHP session starts.

Vespula Session also includes a SQL-based save handler, SqlSaveHandler, for storing session data in a database.

Basic session data

The Session class provides get(), set(), and unset() methods for working with values in the default segment.

Storing values

Use set() to store a value:

$session->set('username', 'juser');
$session->set('user_id', 123);

Values are stored in the default segment.

Retrieving values

Use get() to retrieve a stored value:

$username = $session->get('username');

You can also provide a default value to return when the key does not exist:

$theme = $session->get('theme', 'light');

Removing values

Use unset() to remove an individual value:

$session->unset('username');

Flash messages

Flash messages are session values intended to be retrieved once and then removed. They are useful for displaying notifications after an operation such as a form submission or redirect.

Setting a flash message

Use setFlash() to store a message:

$session->setFlash('success', 'Your changes have been saved.');

Retrieving a flash message

Use getFlash() to retrieve the message:

$message = $session->getFlash('success');

if ($message !== null) {
    echo $message;
}

Retrieving a flash message removes it from the session. Subsequent calls using the same key will return null unless another message has been stored.

Flash messages are stored in the default segment.

CSRF tokens

Vespula Session includes CSRF token generation and validation methods.

CSRF tokens can help protect forms and other state-changing requests against Cross-Site Request Forgery attacks.

Creating a token

Use createCsrfToken() to generate a token:

$token = $session->createCsrfToken();

The token is stored in the default segment under the key csrf_token and returned as a string.

You can provide a custom key when creating a token. This allows multiple CSRF tokens to be stored independently in the same segment:

$loginToken = $session->createCsrfToken('login_token');
$profileToken = $session->createCsrfToken('profile_token');

The key cannot be an empty string.

Include the token in your form as a hidden field:

<input type="hidden" name="csrf_token" value="<?= htmlspecialchars($token, ENT_QUOTES, 'UTF-8') ?>">

Validating a token

When the form is submitted, retrieve the submitted token and pass it to checkCsrfToken():

$token = $_POST['csrf_token'] ?? '';

$session->checkCsrfToken($token);

The method checks that the token has the expected format and matches the value stored in the session. If the token is invalid, missing from the session, or does not match, an exception is thrown.

By default, a successfully validated token is removed from the session. This means the token can only be used once.

You can disable automatic removal by passing false as the third argument:

$session->checkCsrfToken($token, 'csrf_token', false);

You can also specify a custom key when validating a token. The key must match the one used when creating it:

$session->checkCsrfToken($loginToken, 'login_token');

CSRF tokens are stored in the segment on which the methods are called. The Session convenience methods use the default segment, while named segments can manage their own tokens independently.

Working with segments

Segments provide a way to organize session data into separate groups.

The default segment is used by the convenience methods on the Session class, such as get(), set(), unset(), setFlash(), and getFlash().

You can also create or retrieve named segments using getSegment().

Creating a named segment

$auth = $session->getSegment('auth');

If the segment does not already exist, it will be created.

Calling getSegment() again with the same name returns the existing segment object.

Storing and retrieving segment values

A segment provides the same basic data methods as the main session class:

$auth = $session->getSegment('auth');

// Store authentication information
$auth->set('user_id', 123);
$auth->set('username', 'juser');

// Retrieve authentication information
$userId = $auth->get('user_id');

// Remove a value
$auth->unset('username');

Each segment maintains its own collection of keys, so values in one segment do not overwrite values in another.

Segment-specific flash messages and CSRF tokens

Segments also provide their own flash message and CSRF token methods:

$auth = $session->getSegment('auth');

// Flash message
$auth->setFlash('message', 'You have been logged in.');
$message = $auth->getFlash('message');

// CSRF token
$token = $auth->createCsrfToken();
$auth->checkCsrfToken($token);

This can be useful when different parts of an application need to keep their session-related data separate.

Clearing session data

The unsetSessionContainer() method removes the entire Vespula Session container and clears the cached segment objects:

$session->unsetSessionContainer();

This removes all data stored by the library, including data in named segments. It does not clear unrelated values in the PHP $_SESSION array or delete the session cookie.

Be careful when using this method: it affects every segment, not just the default segment.

Regenerating the session ID

After successful authentication, it is good practice to regenerate the PHP session ID to help protect against session fixation.

Use regenerateId():

$session->regenerateId();

By default, the old session data is not immediately deleted. You can request that PHP delete the old session data by passing true:

$session->regenerateId(true);

This method can only be called after the session has started.

Checking session status

Vespula Session maintains its own status to distinguish between an active session and one whose library-managed data has expired.

Use isActive() and isIdle() to check the status:

if ($session->isIdle()) {
    // The library's session container has expired.
    // The application may need to require authentication again.
}

if ($session->isActive()) {
    // The library's session container is active.
}

An idle session does not necessarily mean that the underlying PHP session has stopped. The PHP session remains active, but the library’s container has been cleared.