Skip to content

Leaf Session

Given that HTTP-driven applications lack statefulness, sessions offer a means of retaining user-related data throughout multiple requests. Usually, this user information is stored in some sort of persistent storage so it can be accessed on subsequent requests.

Although using sessions in PHP is fairly straightforward, it can be a bit cumbersome at times. Leaf session aims to make working with sessions in PHP much easier, more enjoyable, and more testable. For that reason, Leaf provides the session module to help you manage sessions in your Leaf apps. Leaf session is 100% compatible with native PHP sessions.

Installation

You can install leaf session with the Leaf CLI tool:

leaf install session

or with composer:

composer require leafs/session

Functional Mode

When using Leaf session in a Leaf 3 app, you can use the functional mode. This allows you to use the session module without having to initialize it. This gives you access to the session() and flash() helper functions.

Starting a new session

Leaf's session module smartly handles session initialization. It checks if a session has already been started and starts a new one if it hasn't. This means you don't have to worry about starting a session before using it. Note that Leaf will not start a session until you actually use it. This is to prevent unnecessary session initialization.

You also don't have to worry about messing up your sessions since Leaf session is 100% compatible with native PHP sessions.

Manually starting a session

If you want to manually start a session, you can use the start() method.

$session = new Leaf\Http\Session;

...

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

Retrieving session data

Leaf session provides 3 ways to retrieve session data:

  • The get() method
  • The retrieve() method
  • The body() method

The get() method

get() is a simple method that returns a session value. It takes in 3 parameters:

  • The name of the value to return. It works just like how $_SESSION['key'] does.
  • The default value to use if it doesn't exist.
  • A boolean value indicating whether to sanitize the value or not. It has a default value of true.
$session = new Leaf\Http\Session;

...

$item = $session->get('item');
$item = $session->get('item', 'default value');
$item = $session->get('item', 'default value', false);
$item = session()->get('item');
$item = session()->get('item', 'default value');
$item = session()->get('item', 'default value', false);

You can also return many fields at once from the session by passing an array of keys:





 





$session = new Leaf\Http\Session;

...

$user = $session->get(['username', 'email']);

...

echo $user['username'];
 





$user = session()->get(['username', 'email']);

...

echo $user['username'];

The retrieve() method

retrieve() returns the requested value just like get() above and then immediately removes it from the session, so it can only be retrieved once.

It takes in three parameters:

  • The name of the value to return. It works just like how $_SESSION['key'] does.
  • The default value to use if it doesn't exist.
  • A boolean value indicating whether to sanitize the value or not. It has a default value of true.
$session = new Leaf\Http\Session;

...

$item = $session->retrieve('item');
$item = $session->retrieve('item', 'default value');
$item = $session->retrieve('item', 'default value', false);
$item = session()->retrieve('item');
$item = session()->retrieve('item', 'default value');
$item = session()->retrieve('item', 'default value', false);

The body() method

This method returns the {key => value} pairs of all the session data including any CSRF data as an associative array.

$session = new Leaf\Http\Session;

...

$body = $session->body();
$body = session()->body();

Check if a session value exists

You can check if a session value exists with the has() method. It takes in the name of the value to check for and returns a boolean value.

$session = new Leaf\Http\Session;

...

if ($session->has('item')) {
  // do something
}
if (session()->has('item')) {
  // do something
}

By default, has() will return true ONLY if the value exists and is NOT empty. You can change this behaviour by passing in false as the second parameter. This boolean value indicates whether to check if the value is empty or not. It has a default value of true.

$session = new Leaf\Http\Session;

...

if ($session->has('item', false)) {
  // do something
}
if (session()->has('item', false)) {
  // do something
}

Setting session data

The session module provides a simple way to set session data using the set() method. It takes in two parameters:

  • The name of the value to set.
  • The value to set.
$session = new Leaf\Http\Session;

...

$session->set('item', 'value');
session()->set('item', 'value');

You can also set multiple values at once by passing in an array:

$session = new Leaf\Http\Session;

...

$session->set([
  'item1' => 'value1',
  'item2' => 'value2'
]);
session()->set([
  'item1' => 'value1',
  'item2' => 'value2'
]);

Removing session data

Leaf provides a simple unset() method to remove session data. It takes in the name of the value to remove.

$session = new Leaf\Http\Session;

...

// remove single item
$session->unset('email');

// remove multiple items
$session->unset(['name', 'email']);
// remove single item
session()->unset('email');

// remove multiple items
session()->unset(['name', 'email']);

We also added the delete() method as an alias for unset(). They both do the same thing.

$session = new Leaf\Http\Session;

...

// remove single item
$session->delete('email');

// remove multiple items
$session->delete(['name', 'email']);
// remove single item
session()->delete('email');

// remove multiple items
session()->delete(['name', 'email']);

Wiping session data

Leaf Session allows you to wipe all session data with the clear() method. This method completely deletes all session information, but does not destroy the session itself.

$session = new Leaf\Http\Session;

...

$session->clear();

echo json_encode($_SESSION); // {}
session()->clear();

echo json_encode($_SESSION); // {}

Working with Arrays

Leaf session allows you to neatly handle working with arrays in session. You can set, retrieve and validate session values from arrays by using the dot notation:

$session = new Leaf\Http\Session;

...

// $user = ['username' => 'leaf', 'email' => 'leaf@example'];

$username = $session->get('user.username');
$email = $session->get('user.email');
// $user = ['username' => 'leaf', 'email' => 'leaf@example'];

$username = session()->get('user.username');
$email = session()->get('user.email');

This works for retrieve(), has(), set() and unset() as well.

has:

$session = new Leaf\Http\Session;

...

if ($session->has('user.username')) {
  // do something
}

// allow empty values
if ($session->has('user.username', false)) {
  // do something
}
if (session()->has('user.username')) {
  // do something
}

// allow empty values
if (session()->has('user.username', false)) {
  // do something
}

Set:

$session = new Leaf\Http\Session;

...

$session->set('user.username', 'leaf');
session()->set('user.username', 'leaf');

Unset:

$session = new Leaf\Http\Session;

...

$session->unset('user.username');
session()->unset('user.username');

Session flash

Leaf session also provides built-in support for flash messages. Flash messages are temporary messages that are displayed to the user after an action has been performed. They are usually used to display success or error messages to the user.

$session = new Leaf\Http\Session;

$session->flash("my flash message");

echo $session->flash(); // my flash message
session()->flash("my flash message");

echo session()->flash(); // my flash message

For more advanced uses of flash messages, you can check out the Flash Session docs.

Session Internals

Leaf session provides a few methods to help you manage sessions. These methods are:

reset()

You can use the reset() method to re-initialize a session.

$app->post('/session/reset', function () use($session) {
  $session->reset();
});
app()->post('/session/reset', function () {
  session()->reset();
});

id()

id() sets and/or returns the current session id. It takes in an optional parameter: the ID to overwrite the session id.

$id = $session->id();
$id = session()->id();

If the session id is not set, this will generate and return a new session id. However, if the session id is already set, it will just return it.

You can also set your own session id with this syntax below. It will be returned as well, so you can keep it in a variable.

$id = $session->id("new session id");
$id = session()->id("new session id");

regenerate()

This method generates a new session id. It takes in a boolean parameter which indicates whether to delete all session data or not (has a default of false)

$session->regenerate();
$session->regenerate(false);
$session->regenerate(true); // will clear all session data
session()->regenerate();
session()->regenerate(false);
session()->regenerate(true); // will clear all session data

destroy()

You can end a session with destroy.

$session->destroy();
session()->destroy();

encode()

This feature allows you to encode the current session data as a string.

$sessionString = $session->encode();
$sessionString = session()->encode();

decode()

You can also decode a serialized session using the decode() method. It takes in the string to decode and returns true on success, false on failure.

$success = $session->decode($sessionString);
$success = session()->decode($sessionString);
Leaf Session has loaded