Skip to content

Leaf Session

Leaf offers simple session management to help you quickly build your apps and APIs. You can quickly install leaf session with composer or leaf cli.

leaf install session

or with composer:

composer require leafs/session

Using Session

Functional mode

Leaf session also hooks into leaf 3's functional mode. If you are using leaf 3, then this is the fastest way to use the session class.

session

session is a global method that can be used to create a session or return the session object.

session()->set("name", "Michael");

With the above example, no session already exists, so leaf session will create a new one and set the name variable.

You can call any session method on the session function:

session()->destroy();

flash

This is a simple class for getting and setting flash data or returning the leaf flash object.

# return leaf session flash object
flash()->set("This is a message");

Session Class

You can quickly get started with Leaf session by using the Leaf\Http\Session class.


require __DIR__ . "/vendor/autoload.php";

$app = new Leaf\App;
$session = new Leaf\Http\Session;

$app->get("/text", function () use($session) {
  $session->set("name", "Michael Darko");
});

Starting a new session

A new session is started or an old one continued when you instanciate the Leaf\Http\Session.

// new session not started
$session = new Leaf\Http\Session(false);

// new session/continue session
$session = new Leaf\Http\Session;

// new session/continue session
$session = new Leaf\Http\Session(true);

Since we want to avoid sessions conflicting, Leaf allows you to choose whether you want to start a new session on init. This also allows smooth integration with native PHP sessions, so you can always switch to Leaf sessions when you're ready.

Also, since leaf session is 100% compatible with native PHP sessions, you can use the session_start method if you need to.

When using leaf sessions staticly, there's no need for the above methods, just go straight for which ever you need to use.

$sessionBody = Leaf\Http\Session::body();

Or

use Leaf\Http\Session;

$sessionBody = Session::body();

Leaf Session Methods

From this point on you'll be able to use everything Leaf Sessions have to offer. Let's look at the session methods.

set

set simply sets new native session variables for your app.

$session->set("username", $username);
session()->set("username", $username);

Setting multiple values

set can take in an array if you wish to set multiple values or just want to use one.

$session->set([
  "username" => $username,
  "mobile_number" => $mobile_number
]);
session()->set([
  "username" => $username,
  "mobile_number" => $mobile_number
]);

get

get is a simple method that returns a session value. It takes in one parameter: the name of the param passed into the app through the session It works just like how $_SESSION['key'] does.

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

Multiple Get

You can also return many fields at once from the session:

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

Security Fixes

set has also received a bunch of security fixes which prevent maliscious scripts from being passed into your application. You can choose to turn this feature off, maybe for html values:

// turn off sanitize
$html = $session->get("blog", false);
// turn off sanitize
$html = session()->get("blog", false);

retrieve

retrieve returns the requested value and removes it from the session, just like calling get first and then unset for the same key.

It takes in two parameters:

  • the name of the param you want to get It works just like how $_SESSION['key'] does
  • The default value to use if it doesn't exist.
$username = $session->retrieve("username");
$username = session()->retrieve("username");

body

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

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

unset

unset simply deletes a session variable. You can also delete multiple values at once.

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

// multiple values
$session->unset(['name', 'email']);
// single value
session()->unset('email');

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

reset

reset simply re-initialises 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();

So 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

regenerate simply 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);

Session flash

Leaf now provides extensive support for flash messages utilizing Leaf\Flash. This functionality is now available on the session method in the form of flash. You can set and get flash messages using this method.

$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

Error Handling

If any of the above methods fail an operation, false is returned and an error is left in the Leaf\Http\Session local state. This error or errors can be returned by calling the errors method.

$user = $session->get("user");

if (!$user) $response->exit($session->errors());
$user = session()->get("user");

if (!$user) {
  response()->exit(session()->errors());
}

As you can see, you'd manually need to throw errors, this gives you more flexibility in web apps, so instead of throwing session errors, you might do something like this:

<?php
// ...
foreach ($session->errors() as $error => $value) {
  echo "<b>{$value}</b>";
}
<?php
// ...
foreach (session()->errors() as $error => $value) {
  echo "<b>{$value}</b>";
}
Leaf Session has loaded