Skip to content

Session Class Documentation

Benyamin Khalife edited this page Jun 28, 2023 · 1 revision

Webrium\Session

Webrium\Session is a class that provides utility functions for working with PHP sessions. It allows you to easily manage session variables, set the session path, start and stop sessions, and more.

Usage

Start Session

To start a new session or resume an existing one, call the start method. If the session has already started, this method does nothing.

Session::start();

Get or Set Session ID

You can get the current session ID using the id method with no parameters. To set a new session ID, pass the new ID as a parameter.

$current_session_id = Session::id();
$new_session_id = Session::id('new_session_id');

Get or Set Session Name

Similarly to the session ID, you can get the current session name using the name method with no parameters. To set a new session name, pass the new name as a parameter.

$current_session_name = Session::name();
$new_session_name = Session::name('new_session_name');

Set Session Variables

To set session variables, use the set method. You can either pass a single variable name and value, or an associative array of variable names and values.

Session::set('name', 'John Doe');

// OR

Session::set([
  'name' => 'John Doe',
  'age' => 30,
]);

Get Session Variables

To get the value of a session variable, use the get method. If the variable does not exist, you can specify a default value to return.

$name = Session::get('name', 'Unknown');
$age = Session::get('age', 0);

Get and Remove Session Variables

The once method allows you to get the value of a session variable once and then remove it from the session.

$name = Session::once('name', 'Unknown');

Get All Session Variables

To retrieve all session variables as an associative array, use the all method.

$session_variables = Session::all();

Remove Session Variables

To remove a session variable, use the remove method.

Session::remove('name');

Clear Session

To clear all session variables and destroy the session, call the clear method.

Session::clear();

Set Session Lifetime

You can set the session cookie lifetime in seconds using the lifetime method.

Session::lifetime(3600); // Set session lifetime to 1 hour

Set Path

Before starting a session, you can set the path where session files will be stored using the set_path method. This is an optional step, as the default path is used if not specified.

By default, in the Webrium framework, the path to store sessions is set to 'storage/Framework/Sessions'. If needed, you can modify this path by editing the Config.php file.

Session::set_path('/path/to/session/files');