PHP Luminova: Backend Sessions and Client Login Session Management
The Session class provides a set of methods to simplify session management in your Luminova application. It offers convenient methods for storing, retrieving, and manipulating session data.
The Luminova backend Session
manager is a useful component designed to simplify managing user data and logins of your in PHP session or cookie storage for Luminova web applications. It provides methods to enhance the storage and retrieval of session data, enabling applications to maintain stateful interactions with users across multiple requests. The session manager supports two distinct storage managers:
Luminova\Sessions\Manager\Session
Luminova\Sessions\Manager\Cookie
Additionally, it offers two session handler implementations:
Luminova\Sessions\Handler\Database
Luminova\Sessions\Handler\Filesystem
This flexibility allows developers to choose the most suitable storage mechanism and handler based on their application's requirements.
Storage Managers
The storage managers in Luminova Luminova\Sessions\Manager\Session
and Luminova\Sessions\Manager\Cookie
, handle the storing and retrieval of session data. They provide features to define a base storage table name through the session configuration class (App\Config\Session->tableIndex
), where all application session data is stored. These managers also allow customization of the session storage name, which controls where the session instance stores, retrieves, and manages data in application session table tableIndex
.
Session Storage Manager
The Luminova\Sessions\Manager\Session
manager uses PHP's default $_SESSION
superglobal to store and retrieve session data, ensuring seamless integration with standard PHP session handling.
Cookie Storage Manager
The Luminova\Sessions\Manager\Cookie
manager uses PHP's setcookie
and $_COOKIE
mechanisms to manage session data, offering an alternative for applications that prefer cookie-based storage.
Session Handlers
Luminova provides two session handler implementations Luminova\Sessions\Handler\Database and Luminova\Sessions\Handler\Filesystem. These handlers override PHP's default session handling, enabling the storage of session data in a database or filesystem. They also support ip address binding, data encryption and decryption, allowing secure transfer and management of session data. Encrypted session data can only be decrypted by applications using the same encryption key.
Database Handler
The Luminova\Sessions\Handler\Database
allows session data to be stored in a database, providing scalability and centralized session management.
Filesystem Handler
The Luminova\Sessions\Handler\Filesystem
stores session data in the filesystem, offering simplicity and ease of use for smaller-scale applications.
Custom Session Handlers
In addition to the built-in handlers, Luminova provides a Luminova\Base\BaseSessionHandler class. Developers can extend this abstract base class to implement custom session handlers to meet their specific application needs.
Note: The
Luminova\Sessions\Session
class is designed for backend session management, prioritizing enhanced security and scalability.
Examples
Initializes the session storage driver of your choice.
use Luminova\Sessions\Session;
use Luminova\Sessions\Manager\Session as SessionManager;
$session = new Session(new SessionManager());
$session->start();
With Cookie Manager
Cookie manager, this manager will store your user information in cookie storage which is client-side storage.
use Luminova\Sessions\Session;
use Luminova\Sessions\Manager\Cookie as CookieManager;
$session = new Session(new CookieManager());
$session->start();
With Database Handler
This will overwrite the default PHP session storage with a database handler. For more information about the database handler, refer to the Database Session Handler Documentation.
use Luminova\Sessions\Session;
use Luminova\Sessions\Handler\Database;
$session = new Session();
$session->setHandler(new Database('tableName'));
$session->start();
Note: By default access to
JavaScript
is not allowed on and cookie should only be transmitted over secureHTTPS
connection.
Class Definition
- Class namespace:
\Luminova\Sessions\Session
- This class implements: \Luminova\Interface\LazyInterface
Methods
constructor
Initializes session class with your preferred manager class, such as Luminova\Sessions\Manager\Session
or Luminova\Sessions\Manager\Cookie
.
This constructor sets up the session manager to handle user login and backend session management.It allows for an optional custom session manager and session handler to be provided or defaults to the standard manager.
If not provided, the default \Luminova\Sessions\Manager\Session
will be used as default.
public __construct(?\Luminova\Interface\SessionManagerInterface $manager = null): mixed
Parameters:
Parameter | Type | Description |
---|---|---|
$manager | SessionManagerInterface|null | Optional. A custom session manager instance.. |
Note: When no custom manager is provided, the default session manager is automatically initialized and configured using the session configuration settings.
getInstance
Singleton method to return an instance of the Session class.
public static getInstance(?\Luminova\Interface\SessionManagerInterface $manager = null): static
Parameters:
Parameter | Type | Description |
---|---|---|
$manager | SessionManagerInterface|null | The session manager class. |
Return Value:
static
- Return a shared instance of session class.
setHandler
Sets the session save handler.
This method allows you to set a custom save handler for the session. The save handler is responsible for storing and retrieving session data.
public setHandler(Luminova\Base\BaseSessionHandler $handler): self
Parameters:
Parameter | Type | Description |
---|---|---|
$handler | \Luminova\Base\BaseSessionHandler | The custom session save handler instance. |
Return Value:
static
- Return the Session class instance.
Reference
Example
Using the database handler:
use Luminova\Sessions\Handler\Database;
$session->setHandler(new Database('tableName'));
Using the filesystem handler:
use Luminova\Sessions\Handler\Filesystem;
$session->setHandler(new Filesystem('/writeable/session/'));
toArray
Retrieve data as an array from the current session storage.
public toArray(?string $index = null): array
Parameters:
Parameter | Type | Description |
---|---|---|
$index | string|null | Optional key to retrieve. |
Return Value:
array
- Return an array representation of data
toObject
Retrieves data as an object from the current session storage.
public toObject(?string $index = null): object
Parameters:
Parameter | Type | Description |
---|---|---|
$index | string|null | Optional key to retrieve. |
Return Value:
object
- Return an object representation of data.
toExport
Retrieves all stored session data as an array or object.
public toExport(string $type = 'array'): array|object
Parameters:
Parameter | Type | Description |
---|---|---|
$type | string | The return session data type, it can be either object or array (default is 'array'). |
Return Value:
array|object
- Return all the stored session data as either an array or object.
setManager
Sets the session manager.
public setManager(\Luminova\Interface\SessionManagerInterface $manager): void
Parameters:
Parameter | Type | Description |
---|---|---|
$manager | SessionManagerInterface | The session manager to set. |
getManager
Retrieves the session storage manager instance (CookieManager
or SessionManager
).
public getManager(): ?\Luminova\Interface\SessionManagerInterface
Return Value:
\Luminova\Interface\SessionManagerInterface|null
- The storage manager instance otherwise null if not set.
setStorage
Sets the storage name to store and retrieve items from.Each time you call method for CRUD
operations it will use your storage, if you want to to change storage you can set new storage name before calling methods.
public setStorage(string $storage): self
Parameters:
Parameter | Type | Description |
---|---|---|
$storage | string | The storage key to set. |
Return Value:
Session
- Return session class instance.
getStorage
Retrieves the current session storage name.
public getStorage(): string
Return Value:
string
- Return the current storage name.
get
Retrieves a value from the session storage.
public get(string $key, mixed $default = null): mixed
Parameters:
Parameter | Type | Description |
---|---|---|
$key | string | The key to identify the session data. |
$default | mixed | Default value if the key is not found. |
Return Value:
mixed
- Return the retrieved data.
getFrom
Retrieves an item from a specified session storage instance.
public getFrom(string $index, string $storage): mixed
Parameters:
Parameter | Type | Description |
---|---|---|
$index | string | The key to retrieve. |
$storage | string | The storage key name. |
Return Value:
mixed
- Return the retrieved data.
setTo
Sets an item to a specified session storage instance.
public setTo(string $index, mixed $data, string $storage): self
Parameters:
Parameter | Type | Description |
---|---|---|
$index | string | The key to set. |
$data | mixed | The data to set. |
$storage | string | The storage key name. |
Return Value:
self
- Return session class instance.
online
Checks if user has successfully logged in online.
public online(?string $storage = null): bool
Parameters:
Parameter | Type | Description |
---|---|---|
$storage | string|null | optional storage instance key |
Return Value:
bool
- Returns true if the session user is online, false otherwise.
Optionally, specify a storage name to check; otherwise, it checks the current storage.
ssid
Retrieves the user's login session ID.
public ssid(): ?string
Return Value:
string|null
- Returns the session ID or null if not logged in.
A unique session ID is automatically generated once synchronize() is called.
ssDate
Retrieves the user's login session datetime in ISO 8601 format.
public ssDate(): ?string
Return Value:
string|null
- Returns the session login date-time or null if not logged in.
The session datetime is automatically generated once synchronize() is called.
set
Sets a value in the session storage by key.
This method saves or updates a value in the session using the specified key.If the key already exists, its value will be overwritten with the new value.
public set(string $key, mixed $value): self
Parameters:
Parameter | Type | Description |
---|---|---|
$key | string | The key to identify the session data. |
$value | mixed | The value to associate with the specified key. |
Return Value:
Session
- Return session class instance.
add
Adds a value to the session storage without overwriting existing keys.
This method attempts to add a new key-value pair to the session.If the specified key already exists in the session storage, the method does not modify the value and sets the status to false
. Otherwise, it adds the new key-value pair and sets the status to true
.
public add(string $key, mixed $value, bool &$status = false): self
Parameters:
Parameter | Type | Description |
---|---|---|
$key | string | The key to identify the session data. |
$value | mixed | The value to associate with the specified key. |
$status | bool | A reference variable to indicate whether the operation succeeded (true ) or failed (false ). |
Return Value:
self
- Returns the current Session instance.
remove
Remove a key from the session storage by passing the key.
public remove(string $key): self
Parameters:
Parameter | Type | Description |
---|---|---|
$key | string | The session data key to remove. |
Return Value:
Session
- Return session class instance.
clear
Clear all data from session storage by passing the storage key.
public clear(?string $storage = null): self
Parameters:
Parameter | Type | Description |
---|---|---|
$storage | string|null | Optionally pass storage name to clear. |
Return Value:
Session
- Return session class instance.
has
Check if item key exists in session storage.
public has(string $key): bool
Parameters:
Parameter | Type | Description |
---|---|---|
$key | string | Key to check |
Return Value:
boo
- Return true if key exists in session storage else false.
start
To start a session, simply call the start()
method. It initializes the session if it's not already started.This method replaces the default PHP session_start()
, with additional configuration.
public start(?string $ssid = null): void
Parameters:
Parameter | Type | Description |
---|---|---|
$ssid | string|null | Optional specify session identifier from PHP session_id . |
Throws:
- \Luminova\Exceptions\RuntimeException - If an invalid session ID is provided.
Example:
Starting a session with a specified session ID:
namespace App;
use Luminova\Core\CoreApplication;
use Luminova\Sessions\Session;
class Application extends CoreApplication
{
protected ?Session $session = null;
protected function onCreate(): void
{
$this->session = new Session();
$this->session->start('optional_session_id');
}
}
destroy
Clears all data stored in the session storage table $tableIndex
based on your session configuration class.This method differs from PHP's session_destroy()
as it only affects the session table data, not the entire session.
public destroy(): bool
Return Value
bool
- Returns true if session data was successfully destroyed; false otherwise.
Note: This method doesn't behave same way as PHP
session_destroy
.
destroyAll
Clears all data stored in the session for the entire application.This method uses PHP's session_destroy()
and setcookie
to affects the entire session.
public destroyAll(): bool
Return Value:
bool
- Returns true if session data was successfully destroyed; false otherwise.
Note: This will clear all session and cookie data for the entire application.
synchronize
Synchronizes the user's online session, optionally associating it with an IP address.
This method is called once after a successful login to initialize and maintain session data,indicating that the user is online. It can also synchronize the session with a specified IP address, if not provided, the client's current IP address will be used if strict IP validation is enabled in application session configuration.
public synchronize(?string $ip = null): self
Parameters:
Parameter | Type | Description |
---|---|---|
$ip | string|null | Optional. The IP address to associate with the session. |
Return Value:
Session
- Return session class instance.
Note: If the
$strictSessionIp
configuration option is enabled, the session will automatically associate with an IP address. When no IP address is provided, the client's current IP will be detected and used.
Throws:
- \Luminova\Exceptions\LogicException - If strict IP validation is disabled and IP address is provided.
Example:
Synchronizing user login session:
namespace App\Controllers\Http;
use Luminova\Base\BaseController;
class AdminController extends BaseController
{
public function loginAction(): int
{
$username = $this->request->getPost('username');
$password = $this->request->getPost('password');
if($username === 'admin' && $password === 'password'){
$this->app->session->set('username', $username);
$this->app->session->set('email', '[email protected]');
$this->app->session->synchronize();
return response()->json(['success' => true]);
}
return response()->json(['success' => false, 'error' => 'Invalid credentials']);
}
}
ipChanged
Checks if the user's IP address has changed since the last login session.
public ipChanged(?string $storage = null): bool
Parameters:
Parameter | Type | Description |
---|---|---|
$storage | string|null | Optional session storage name to perform the check. |
Return Value:
bool
- Returns false if the user's IP address matches the session login IP, otherwise returns true.
onIpChanged
IP Address Change Listener to detect and respond to user IP changes.
This method monitors the user's IP address during a session and $strictSessionIp
is enabled. If the IP address changes,the specified callback is executed. Based on the callback's return value:
true
: The session is destroyed.false
: The session remains active, allowing manual handling of the IP change event.
public onIpChanged(callable $onChange): self
Parameters:
Parameter | Type | Description |
---|---|---|
$onChange | callable | A callback function to handle the IP change event. The function receives the Session instance, the previous IP,and the current IP as arguments. |
Return Value:
self
- Returns the current Session
instance.
Example
Session IP address change event:
namespace App;
use Luminova\Core\CoreApplication;
use Luminova\Sessions\Session;
class Application extends CoreApplication
{
protected ?Session $session = null;
protected function onCreate(): void
{
$this->session = new Session();
$this->session->start();
$this->session->onIpChanged(function (Session $instance, string $sessionIp, string $currentIp): bool {
// Handle the IP address change event manually
// Destroy the session, or return false to keep it or indication that it been handled
return true;
});
}
}