Luminova Framework

PHP Luminova: Backend Session & User Login Management

Last updated: 2026-10-21 05:32:49

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 Class makes it easier to handle user logins and session data for both Web and CLI applications. Instead of writing low-level session logic yourself, you can use this class to store, retrieve, and manage session data reliably—whether you want to use PHP sessions, cookies, files, or even a database.

With Luminova, you get two main types of session storage managers:

  • Luminova\Sessions\Managers\Session – uses PHP’s built-in session handling ($_SESSION).
  • Luminova\Sessions\Managers\Cookie – stores session data directly in cookies.

And you also get three ready-to-use session handlers:

  • Luminova\Sessions\Handlers\Database – stores sessions in a database.
  • Luminova\Sessions\Handlers\Filesystem – stores sessions in files.
  • Luminova\Sessions\Handlers\ArrayHandler – keeps session data in memory only.

This flexibility means you can pick the storage method that best fits your application, whether it’s a high-traffic website needing a central database, or a CLI tool where temporary in-memory storage is plenty.


Storage Managers

Session Manager (Luminova\Sessions\Managers\Session)This manager uses PHP’s normal $_SESSION superglobal. If you’re already familiar with standard PHP sessions, this will feel natural—it’s just cleaner and more configurable.

Cookie Manager (Luminova\Sessions\Managers\Cookie)This manager stores everything directly in cookies using PHP’s setcookie and $_COOKIE. It’s handy when you want the browser to carry session data around without relying on PHP’s built-in session files.

Both managers allows you to customize where your session data is stored using App\Config\Session->tableIndex. You can also set your own storage name so multiple apps don’t clash in the same table or namespace.


Session Handlers

Sometimes you need more control than PHP’s default session behavior. Luminova provides custom session handlers that completely replace PHP’s internal storage logic:

  • Database Handler (Luminova\Sessions\Handlers\Database)Stores session data in a database table—perfect for scaling across multiple servers.

  • Filesystem Handler (Luminova\Sessions\Handlers\Filesystem)Saves session files on disk—simple and reliable for small or single-server apps.

  • Array Handler (Luminova\Sessions\Handlers\ArrayHandler)Keeps session data in memory only. This is blazing fast, but doesn’t persist between requests. It’s great for testing, CLI tools, or anything that doesn’t need permanent session storage.

All handlers can optionally encrypt data and bind it to an IP address for extra security. Encrypted sessions can only be read by apps using the same encryption key.


Custom Handlers

Need something different? Luminova provides a base class, Luminova\Base\SessionHandler, so you can write your own session storage logic while still plugging into the same system.


Examples

Initializes the session storage driver of your choice.

use Luminova\Sessions\Session;
use Luminova\Sessions\Managers\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\Managers\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\Handlers\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 secure HTTPS connection.


Class Definition


Class Constants

ConstantValueDescription
GUARD_ANY0At least one required role must exist in the user's roles.
GUARD_ALL1All required roles must be present in the user's roles (extras allowed).
GUARD_EXACT2Exact match — all and only the specified roles must exist.
GUARD_NONE3None of the given roles should be present (e.g., guest access only).
DISABLED0Sessions are disabled.
NONE1Sessions are enabled, but no session currently exists.
ACTIVE2A session is currently active.

Methods

constructor

Initializes the session class with your preferred session manager and configuration.

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 configuration object to be provided, otherwise the defaults are used.

public __construct(
    Luminova\Interface\SessionManagerInterface $manager = new SessionManager(),
    App\Config\Session $config = new SessionConfig()
)

Parameters:

ParameterTypeDescription
$managerSessionManagerInterfaceOptional. A custom session manager instance (default: Luminova\Sessions\Managers\Session).
$configApp\Config\SessionOptional. Session configuration object (default: App\Config\Session).

Note: The manager is configured automatically using the supplied session configuration, including its storage namespace and strict-mode setting.


getInstance

Singleton method to return a shared instance of the Session class.

public static getInstance(
    ?Luminova\Interface\SessionManagerInterface $manager = null,
    ?App\Config\Session $config = null
): static

Parameters:

ParameterTypeDescription
$managerSessionManagerInterface|nullOptional. A custom session manager instance. Only used the first time the singleton is initialized.
$configApp\Config\Session|nullOptional. A custom session configuration. Only used the first time the singleton is initialized.

Return Value:

static - Return the shared instance of the session class.


from

Creates a new session instance configured for a specific storage.

The returned instance is independent of any existing Session instance. Use setStorage() instead if you want to change the storage of an existing instance.

public static from(
    string $storage,
    ?Luminova\Interface\SessionManagerInterface $manager = null,
    ?App\Config\Session $config = null
): static

Parameters:

ParameterTypeDescription
$storagestringThe session storage name.
$managerSessionManagerInterface|nullOptional session manager (default: Luminova\Sessions\Managers\Session).
$configApp\Config\Session|nullOptional session configuration (default: App\Config\Session).

Return Value:

static - Return a new Session instance configured for the specified storage.

Example:

$session = Session::from('user-profile');
$session->start();

toSessionId

Converts a string into a valid PHP session ID, based on the current PHP session configuration.

Generates a session ID that conforms to session.sid_bits_per_character and session.sid_length.

Supported bit modes:

  • 4 bits: hexadecimal characters [0-9a-f]
  • 5 bits: base32-like characters [0-9a-v]
  • 6 bits: extended base64-like character set
public static toSessionId(string $input, string $algo = 'sha256'): ?string

Parameters:

ParameterTypeDescription
$inputstringThe input string to convert.
$algostringThe hashing algorithm to use if the input is not already a 64-character hex hash (default: sha256).

Return Value:

string|null - Return the generated session ID, or null on failure.

Throws:

Examples:

Convert a CLI system ID to a PHP session ID:

$sid = Session::toSessionId(Luminova\Command\Terminal::getSystemId());

Convert an arbitrary string to a session ID:

$sid = Session::toSessionId('user-id');

getManager

Retrieves the current session storage manager instance.

This method returns the session manager instance responsible for handling session data, either Luminova\Sessions\Managers\Cookie or Luminova\Sessions\Managers\Session.

public getManager(): ?Luminova\Interface\SessionManagerInterface

Return Value:

SessionManagerInterface|null - Return the current session manager instance, or null if not set.


getStorage

Retrieves the current session storage name.

public getStorage(): string

Return Value:

string - Return the current session storage name.


getName

Retrieves the session cookie name.

If a custom cookie name is set in the configuration, it will be returned; otherwise, the native PHP session name is used, falling back to PHPSESSID.

public getName(): string

Return Value:

string - Return the session cookie name.


getResult

Retrieves all session data in the specified format.

public getResult(bool $asObject = false): array|object

Parameters:

ParameterTypeDescription
$asObjectboolIf true, return the data as an object, otherwise as an array (default: false).

Return Value:

array|object - Return the stored session data in the requested format.


get

Retrieves a value from the session storage.

public get(string $name, mixed $default = null): mixed

Parameters:

ParameterTypeDescription
$namestringThe session data key.
$defaultmixedThe default value returned if the key does not exist.

Return Value:

mixed - Returns the retrieved session data or the default value if not found.


getId

Retrieves the active PHP session identifier.

public getId(): ?string

Return Value:

string|null - Return the current PHP session identifier, or null when the session is neither active nor online.


getIp

Retrieves the IP address bound to the current login session.

public getIp(): ?string

Return Value:

string|null - Return the stored IP address, or null if not set.


getUserAgent

Retrieves the user agent associated with the login session.

public getUserAgent(): ?string

Return Value:

string|null - Return the user agent string, or null if not set.


getToken

Retrieves the client's online session login token.

This method returns the sha256-hashed token generated when login() is called. It can be used to track the online session state, validate session integrity, or prevent session fixation attacks.

public getToken(): ?string

Return Value:

string|null - Return the sha256-hashed login session token, or null if not logged in.


getDatetime

Retrieves the client login session date and time in ISO 8601 format.

The session datetime is generated automatically when login() is called, marking the moment the session login was established.

public getDatetime(): ?string

Return Value:

string|null - Return the session login datetime in ISO 8601 format, or null if not logged in.


getTimestamp

Retrieves the client login session creation timestamp.

public getTimestamp(): int

Return Value:

int - Return the Unix timestamp when the session was created, or 0 if not logged in.


getExpiration

Retrieves the session expiration timestamp, calculated from the current time plus the configured expiration.

public getExpiration(): int

Return Value:

int - Return the expiration timestamp.


getUpdatedAt

Retrieves the timestamp of the last session update.

public getUpdatedAt(): ?int

Return Value:

int|null - Return the Unix timestamp of the last session update, or null if no update timestamp is recorded.

See Also:

  • touch() – to update the last activity timestamp.
  • isIdleFor() – to check elapsed idle time.

getLastAttempt

Retrieves the timestamp of the last login attempt.

public getLastAttempt(): ?int

Return Value:

int|null - Return the Unix timestamp of the last recorded login attempt, or null if none has been recorded.

See Also: isLoginLocked()


getMeta

Retrieves a session login metadata value.

public getMeta(string $name): mixed

Parameters:

ParameterTypeDescription
$namestringThe metadata key to retrieve.

Return Value:

mixed - Return the metadata value, or null if it does not exist.


getMetadata

Retrieves all session login metadata.

public getMetadata(): array<string,mixed>

Return Value:

array<string,mixed> - Return an associative array containing session metadata.


getAttributes

Retrieves all session user data, excluding internal login metadata.

public getAttributes(): array<string,mixed>

Return Value:

array<string,mixed> - Return an associative array of session data, without the internal metadata entry.


getIpAddresses

Retrieves a list of IP address changes recorded during the session.

public getIpAddresses(): array<int,string>

Return Value:

array<int,string> - Return the list of previously recorded IP addresses, or an empty array if none.


getAttemptTimes

Retrieves the timestamps of recent login attempts.

public getAttemptTimes(): array<int,float>

Return Value:

array<int,float> - Return the Unix timestamps recorded for recent login attempts.

See Also: attempt(), isRapidAttempts()


getRoles

Gets the list of roles assigned to the current session user.

Retrieves roles from the session metadata. Returns an empty array if no roles are set.

public getRoles(): array<int, string|int>

Return Value:

array<int,string|int> - Return a list of assigned roles, or an empty array if none.

Example:

$roles = $session->getRoles();

if (in_array('admin', $roles)) {
    // grant admin access
}

setHandler

Sets the session save handler responsible for managing session storage.

This method allows specifying a custom session save handler, such as a database, array, or filesystem-based handler, to control how session data is stored and retrieved.

The session save handler can be one of:

  • Luminova\Sessions\Handlers\Database: Stores session data in a database.
  • Luminova\Sessions\Handlers\Filesystem: Saves session data in files.
  • Luminova\Sessions\Handlers\ArrayHandler: Stores session data temporarily in an array.
public setHandler(Luminova\Base\SessionHandler $handler): self

Parameters:

ParameterTypeDescription
$handlerLuminova\Base\SessionHandlerThe session save handler instance.

Return Value:

self - Returns the instance of session class.

Reference

For more details on session handlers, refer to the following documentation:

Example

Using the database handler:

use Luminova\Sessions\Handlers\Database;

$session->setHandler(new Database('tableName'));

Using the filesystem handler:

use Luminova\Sessions\Handlers\Filesystem;

$session->setHandler(new Filesystem('/writeable/session/'));

setManager

Sets the session manager that controls the underlying storage engine for session data.

Unlike setHandler(), which is only applicable when using Luminova\Sessions\Managers\Session, this method allows specifying a session manager to determine where session data is stored.

The session manager can be either:

  • Luminova\Sessions\Managers\Cookie: Stores session data securely in client-side cookies.
  • Luminova\Sessions\Managers\Session: Uses PHP's default $_SESSION storage.
public setManager(Luminova\Interface\SessionManagerInterface $manager): self

Parameters:

ParameterTypeDescription
$managerSessionManagerInterfaceThe session manager instance to set.

Return Value:

self - Returns the instance of session class.


setStorage

Sets the storage name for storing and retrieving session data.

This method allows you to define or override the session storage name under which session data will be managed.

public setStorage(string $storage): self

Parameters:

ParameterTypeDescription
$storagestringThe session storage name to set.

Return Value:

self - Returns the instance of session class.


setNamespace

Set the storage namespace.

Unlike setStorage(), this allows data to be stored under a different namespace within the same storage.

public setNamespace(?string $namespace): self

Parameters:

ParameterTypeDescription
$namespacestring|nullThe namespace, or null to use default.

Return Value:

self - Returns the instance of session class.

Throws:


set

Sets a value in the session storage by key.

This method saves or updates a value in the session using the specified key, and refreshes the session's last-activity timestamp. If the key already exists, its value is overwritten.

public set(string $name, mixed $value): self

Parameters:

ParameterTypeDescription
$namestringThe key to identify the session data.
$valuemixedThe value to associate with the specified key.

Return Value:

self - Returns the instance of session class.

Throws:


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, the value is left unmodified and $status is set to false. Otherwise, the value is stored and $status is set to true.

public add(string $name, mixed $value, bool &$status = false): self

Parameters:

ParameterTypeDescription
$namestringThe key to identify the session data.
$valuemixedThe value to associate with the specified key.
$statusboolA reference variable indicating whether the value was added (true) or already existed (false).

Return Value:

self - Returns the instance of session class.


put

Queues a value for batch storage, to be saved when save() is called.

This method stores the value in a temporary pending stack rather than persisting it immediately. If a key already exists in the stack, its value is replaced.

public put(string $name, mixed $value): self

Parameters:

ParameterTypeDescription
$namestringThe key to identify the session data.
$valuemixedThe value to associate with the specified key.

Return Value:

self - Returns the instance of session class.

See Also:

  • save() – to persist queued data.
  • dequeue() – to discard queued data.

save

Persists all values queued with put() to session storage.

Once saved, the pending stack is cleared. Returns false immediately when there is nothing queued.

public save(): bool

Return Value:

bool - Return true if the queued data was successfully saved, otherwise false when there was nothing to save.

Throws:

Note: Values stored with set() are persisted immediately and do not need to be saved with this method.


all

Retrieves all session data, including internal login metadata.

public all(): array<string,mixed>

Return Value:

array<string,mixed> - Return the session data stored in the current storage.

See Also:

  • getAttributes() – to retrieve session data without internal metadata.

touch

Updates the session's last activity timestamp.

Refreshes the session activity timestamp without changing other session data.

public touch(?int $timestamp = null): self

Parameters:

ParameterTypeDescription
$timestampint|nullOptional Unix timestamp to record (default: current time).

Return Value:

self - Returns the instance of session class.


close

Commits the current session data.

This method finalizes the session write process by committing any pending changes. Once committed, the session is considered closed and cannot be modified until restarted.

public close(): bool

Return Value:

bool - Return true on success, false if the operation failed.

See Also:

  • start() – to start or restart the session.

dequeue

Clears all queued session data without saving.

Use this to discard changes queued via put() before calling save().

public dequeue(): true

Return Value:

true - Always returns true.


is

Checks whether the current session or cookie status matches the given status.

public is(int $status = Session::ACTIVE): bool

Parameters:

ParameterTypeDescription
$statusintThe session status to check (default: Session::ACTIVE).
- Session::DISABLED – Sessions are disabled.
- Session::NONE – Sessions are enabled, but no session exists.
- Session::ACTIVE – A session is currently active.

Return Value:

bool - Returns true if the current session status matches the given status, otherwise false.


isStarted

Checks whether the session has been started.

This returns true after start() has been called successfully in the current request lifecycle.

public isStarted(): bool

Return Value:

bool - Returns true if the session has started, otherwise false.


isOnline

Checks whether the session user is currently online.

This method verifies whether login() has been called and the login metadata is valid, meaning the session user is considered online.

public isOnline(): bool

Return Value:

bool - Returns true if the session user is online, otherwise false.


isExpired

Checks whether the session is still valid based on elapsed time.

This method determines whether the session has expired based on the last recorded login timestamp. By default, a session is considered still valid if less than 3600 seconds (1 hour) has elapsed.

public isExpired(int $seconds = 3600): bool

Parameters:

ParameterTypeDescription
$secondsintThe time threshold in seconds before the session is considered expired (default: 3600).

Return Value:

bool - Returns true if the session is still valid, false if it has expired.


isIpLocked

Determine whether the session is locked to its originating IP.

public isIpLocked(): bool

Return Value:

bool - Returns true if the session is restricted to its originating IP, otherwise false.


isStrictMode

Determine whether strict session ID mode is enabled.

Checks if $config->useStrictMode, strict mode is enabled in session configuration.

public isStrictMode(): bool

Return Value:

bool - Returns true if strict session ID mode is enabled, otherwise false.


isIpMatch

Determine whether the current IP matches the session IP.

Returns true only when IP locking is enabled and the current IP has notchanged since the session was established.

public isIpMatch(): bool

Return Value:

bool - Returns true if the session IP is valid, otherwise false.


isIdleFor

Determines whether the session has been inactive for the specified duration.

public isIdleFor(int $seconds): bool

Parameters:

ParameterTypeDescription
$secondsintMinimum number of seconds since the last activity.

Return Value:

bool - Returns true if the last recorded activity occurred at least $seconds seconds ago, otherwise false.


isLoginLocked

Determines whether login attempts are currently locked out.

The session is considered locked when the recorded number of login attempts has reached or exceeded $maxAttempts and the lockout period has not yet elapsed since the last attempt.

public isLoginLocked(int $seconds = 300, int $maxAttempts = 3): bool

Parameters:

ParameterTypeDescription
$secondsintNumber of seconds the login remains locked after the maximum attempt count is reached (default: 300).
$maxAttemptsintMaximum number of failed login attempts allowed before the session is locked (default: 3).

Return Value:

bool - Returns true if login attempts are currently locked, otherwise false.

See Also: isRapidAttempts()


isRapidAttempts

Determines whether login attempts are occurring at an unusually high rate.

Checks the recorded login attempt timestamps and returns true when the number of attempts within the specified time window exceeds the allowed threshold.

public isRapidAttempts(int $window = 10, int $maxAttempts = 5): bool

Parameters:

ParameterTypeDescription
$windowintTime window in seconds (default: 10).
$maxAttemptsintMaximum allowed attempts within the window (default: 5).

Return Value:

bool - Returns true if the recent attempt rate is unusually high, otherwise false.

See Also: isLoginLocked()


useStrictMode

Enables or disables strict session ID validation.

When enabled, PHP rejects session IDs that do not already exist in the configured session storage and generates a new session ID instead.

public useStrictMode(bool $enable = true): self

Parameters:

ParameterTypeDescription
$enableboolWhether to enable strict session ID validation (default: true).

Return Value:

self - Returns the instance of session class.


toArray

Retrieves session data as an associative array.

public toArray(?string $name = null): array<string,mixed>

Parameters:

ParameterTypeDescription
$namestring|nullOptional name to retrieve specific data. If null, returns all session data.

Return Value:

array<string,mixed> - Return the session data as an associative array.


toObject

Retrieves session data as an object.

public toObject(?string $name = null): object

Parameters:

ParameterTypeDescription
$namestring|nullOptional name to retrieve specific data. If null, returns all session data.

Return Value:

object - Return the session data as a standard object.


remove

Removes an item from the session storage by key.

public remove(string $name): self

Parameters:

ParameterTypeDescription
$namestringThe item name to remove.

Return Value:

self - Returns the instance of session class.

Throws:


clear

Clears all data from the current session storage.

public clear(): self

Return Value:

self - Returns the instance of session class.

Throws:


has

Checks whether an item key exists in the session storage.

public has(string $name): bool

Parameters:

ParameterTypeDescription
$namestringThe item name to check.

Return Value:

bool - Return true if the key exists in session storage, otherwise false.


attempt

Records or resets the session login attempt count.

Increments the number of recorded login attempts, or resets the count to zero when $reset is true. The attempt count is stored in session metadata.

public attempt(bool $reset = false): true

Parameters:

ParameterTypeDescription
$resetboolIf true, resets the attempt count to zero.

Return Value:

true - Always returns true.

See Also: isLoginLocked()


attempts

Retrieves the number of recorded session login attempts.

public attempts(): int

Return Value:

int - Return the current number of recorded login attempts.

See Also: isLoginLocked()


regenerate

Regenerates the session or cookie identifier.

Generates a new identifier and optionally deletes the data associated with the previous identifier. When the session remains online, the login token is refreshed to match the new identifier.

public regenerate(bool $clearSessionData = false): string|bool

Parameters:

ParameterTypeDescription
$clearSessionDataboolWhether to delete the data associated with the previous identifier (default: false).

Return Value:

string|bool - Return the new session identifier on success, or false if regeneration fails.


setRoles

Sets the roles for the current session user.

Replaces the roles currently assigned to the session with the specified roles. Roles are stored in session metadata when the session is online, and kept in memory otherwise.

public setRoles(array $roles): self

Parameters:

ParameterTypeDescription
$rolesarray<int,string|int>Roles to assign to the session user.

Return Value:

self - Returns the instance of session class.

Throws:

See Also: assignRoles(), inRoles(), getRoles()

Example:

$session->setRoles(['admin', 'editor']);

assignRoles

Adds roles to the current session user's existing roles.

Merges the specified roles with the user's existing roles and removes duplicates. Existing roles are preserved.

public assignRoles(array $roles): self

Parameters:

ParameterTypeDescription
$rolesarray<int,string|int>Roles to add to the session user.

Return Value:

self - Returns the instance of session class.

Throws:

See Also: setRoles(), inRoles(), getRoles()


revokeRoles

Revokes roles from the current session user.

Removes the specified roles from the user's assigned roles while preserving all other roles. The updated roles are stored in session metadata when the session is online.

public revokeRoles(array $roles): self

Parameters:

ParameterTypeDescription
$rolesarray<int,string|int>Roles to revoke from the session user.

Return Value:

self - Returns the instance of session class.

Throws:

See Also: setRoles(), assignRoles(), inRoles(), getRoles()


inRoles

Checks whether the current session user satisfies the specified roles.

Evaluates the user's assigned roles against the required roles using the specified matching mode. Returns false when the session is offline or when the user does not satisfy the role requirements.

Supported matching modes:

  • Session::GUARD_ANY – At least one required role must be assigned.
  • Session::GUARD_ALL – All required roles must be assigned.
  • Session::GUARD_EXACT – The assigned roles must exactly match the required roles.
  • Session::GUARD_NONE – None of the required roles may be assigned.
public inRoles(?array $roles = null, int $mode = Session::GUARD_ANY): bool

Parameters:

ParameterTypeDescription
$rolesarray<int,string|int>|nullRoles to check against the current user. Defaults to the roles set via setRoles().
$modeintRole matching mode (default: Session::GUARD_ANY).

Return Value:

bool - Returns true if the user satisfies the role requirements, otherwise false.

Throws:

Examples:

Allow access if the user has any of the roles:

if (!$session->inRoles(['admin', 'editor'])) {
    // access granted
}

Require all roles:

if (!$session->inRoles(['admin', 'editor'], Session::GUARD_ALL)) {
    // access granted
}

Require exact match:

if (!$session->inRoles(['admin', 'editor'], Session::GUARD_EXACT)) {
    // access granted
}

Deny access if the user has any of the listed roles:

if ($session->inRoles(['banned', 'suspended'], Session::GUARD_NONE)) {
    // access denied
}

onRoleGuard

Registers a callback to handle failed role authorization.

The callback is evaluated during start() and invoked when the session user is online but does not satisfy the configured role requirements. It receives the session instance, the required roles, and the user's currently assigned roles.

public onRoleGuard(
    callable $onDenied,
    ?array $roles = null,
    int $mode = 0
): void

Parameters:

ParameterTypeDescription
$onDeniedcallable(static, array<int,string|int>, array<int,string|int>): voidCallback invoked when the role check fails.
$rolesarray<int,string|int>|nullRoles required for authorization. Defaults to the roles set via setRoles().
$modeintRole matching mode. One of Session::GUARD_* (default: Session::GUARD_ANY).

Return Value:

void

See Also: setRoles(), inRoles()

Example:

$session->onRoleGuard(
    function (Session $session, array $expected, array $subscriptions): void {
        throw new AccessDeniedException('Access not allowed.');
    },
    ['admin'],
    Session::GUARD_ANY
);

onIpChanged

Registers a callback to handle session IP address changes.

The callback is evaluated during start(), monitoring the user's IP address when strict session IP checking is enabled. It's invoked when the IP address changes and is responsible for deciding how to handle the change, including whether to terminate the session. When no callback is registered and the IP changes, the session is logged out automatically.

public onIpChanged(callable $onChange): self

Parameters:

ParameterTypeDescription
$onChangecallable(static $session, string $previousIp, array<int,mixed> $ipChanges): voidCallback invoked when the session IP address changes. Receives the session instance, the previous IP address, and the recorded IP changes.

Return Value:

self - Returns the instance of session class.

Example:

use Luminova\Sessions\Session;

$session = new Session();
$session->onIpChanged(
    function (Session $session, string $previousIp, array $ipChanges): void {
        $session->logout();
    }
);
$session->start();

start

Initializes PHP session configuration and starts the session if it isn't already started.

This method replaces the default PHP session_start(), with additional configuration, security checks, and event listener registration for role guards and IP change detection.

public start(?string $sessionId = null): bool

Parameters:

ParameterTypeDescription
$sessionIdstring|nullOptional session ID to resume when starting the session.

Return Value:

bool - Return true when the session is started or already active, otherwise false.

Throws:

  • \Luminova\Exceptions\RuntimeException - If the session extension is disabled, or if a session save handler was set but the configured manager does not support PHP session save handlers.

Example:

Starting a session with a specified session ID:

namespace App;

use Luminova\Foundation\Core\Application as 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');
    }
}

login

Starts a user's online login session and synchronizes session login metadata.

This method is called once after a successful login to initialize and persist login-related metadata, marking the user as logged in. If strict IP validation is enabled, it associates the session with a specific IP address. Assign roles with setRoles() before calling this method.

public login(?string $ip = null): bool

Parameters:

ParameterTypeDescription
$ipstring|nullOptional IP address to associate with the login session. If omitted and strict session IP validation is enabled, the client's current IP address is used.

Return Value:

bool - Returns true if the login session was successfully started, otherwise false.

Throws:

Example:

Synchronizing a user login session:

// /app/Controllers/Http/AdminController.php

namespace App\Controllers\Http;

use Luminova\Base\Controller;
use function Luminova\Funcs\response;

class AdminController extends Controller
{
    #[Route('admin/login', methods: ['POST'])]
    public function loginAction(): int
    {
        if ($this->app->session->isOnline()) {
            return response()->json(['success' => true]);
        }

        $username = $this->request->getPost('username');
        $password = $this->request->getPost('password');

        // Perform login authentication
        if ($username === 'admin' && $password === 'password') {
            $this->app->session
                ->set('username', $username)
                ->set('email', '[email protected]')
                ->setRoles(['admin', 'editor'])
                ->login();

            return response()->json(['success' => true]);
        }

        $this->app->session->attempt();

        return response()->json(['success' => false, 'error' => 'Invalid credentials']);
    }
}

logout

Logs out the current session user.

Clears the login state and associated login metadata while preserving the session and its other stored data. The session remains available for subsequent use.

public logout(): bool

Return Value:

bool - Returns true if the user is logged out, otherwise false.

See Also: login(), destroy(), close()


destroy

Destroys the current session managed by this instance.

Logs out the current user, clears all session data, regenerates the underlying session or cookie identifier, closes the session manager, and marks this session as inactive.

public destroy(): bool

Return Value:

bool - Returns true if the session was destroyed successfully, otherwise false.

See Also:

  • logout() – to log out while preserving the session.
  • close() – to close the active session without destroying it.

destroyNative

Destroys the current native PHP session and expires its session cookie.

This method operates on the entire native PHP session and does not preserve session data created outside this session manager.

public static destroyNative(): bool

Return Value:

bool - Return true if the session and cookie were successfully destroyed, otherwise false.


configure

Initializes PHP session configuration.

Applies the supplied session settings to PHP's session subsystem. This method must be called before starting a session.

public static configure(App\Config\Session|object|array $config): bool

Parameters:

ParameterTypeDescription
$configApp\Config\Session|object|array{expiration:int,savePath:string,useStrictMode:bool,cookieName:string,sameSite:string,sessionPath:string,sessionDomain:string}Session configuration.

Return Value:

bool - Return true if the configuration was applied, otherwise false.

Throws:

Example:

Session::configure($config);
session_start();

restartIfNeeded

Ensures the session is started.

Returns immediately when the session is already active; otherwise, attempts to start the session.

public restartIfNeeded(): bool

Return Value:

bool - Returns true if the session is already active or was successfully started, otherwise false.


Magic Methods

__get

Retrieves a session value using property syntax.

public __get(string $name): mixed

Parameters:

ParameterTypeDescription
$namestringSession data key.

Return Value:

mixed - The stored session value, or null if the key does not exist.

Example:

$username = $session->username;

__set

Sets a session value using property syntax.

public __set(string $name, mixed $value): void

Parameters:

ParameterTypeDescription
$namestringSession data key.
$valuemixedValue to store.

Return Value:

void

Example:

$session->username = 'admin';

__isset

Determines whether a session value exists and is not null.

public __isset(string $name): bool

Parameters:

ParameterTypeDescription
$namestringSession data key.

Return Value:

bool - Returns true if the value exists and is not null, otherwise false.

Example:

if (isset($session->username)) {
    // ...
}

Full Session Example

This example shows how to configure a shared Session instance at the application level and use it from controllers.

The important distinction is:

  • Application: registers session-wide guards and starts the session.
  • Controller: consumes the session state and handles authentication requests.
  • IP guard: detects a changed client IP and invalidates the session.
  • Role guard: prevents authenticated users from accessing protected resources without the required role.
  • Login flow: handles failed attempts, authentication, role assignment, and session ID regeneration.

Application Session Configuration

Register session-wide listeners before calling Session::start(). These listeners are evaluated when the session starts and therefore must be registered before the application's single session startup.

// /app/Application.php

namespace App;

use Luminova\Foundation\Core\Application as CoreApplication;
use Luminova\Logger\Logger;
use Luminova\Sessions\Session;

class Application extends CoreApplication
{
    public ?Session $session = null;

    protected function onCreate(): void
    {
        $this->session = new Session();

        // Register application-wide session guards before start().
        $this->session->onIpChanged(
            function (
                Session $session,
                string $previousIp,
                array $ipChanges
            ): void {
                Logger::warning('Session IP changed, forcing logout.', [
                    'previous_ip' => $previousIp,
                    'ip_history'  => $ipChanges,
                ]);

                $session->logout();
            }
        );

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

Protected Admin Controller

The controller does not register the IP-change listener because that listener already belongs to the shared application session.

The role guard is also registered against the shared session so that the required role is enforced consistently for the authenticated admin area.

// /app/Controllers/Http/AdminController.php

namespace App\Controllers\Http;

use Luminova\Attributes\Prefix;
use Luminova\Attributes\Route;
use Luminova\Base\Controller;
use Luminova\Sessions\Session;
use Luminova\Exceptions\HttpException;

#[Prefix(pattern: '/admin/(:root)')]
class AdminController extends Controller
{
    protected function onCreate(): void
    {
        if (!$this->session->isOnline()) {
            return;
        }

        $this->session->onRoleGuard(
            function (
                Session $session,
                array $expected,
                array $subscriptions
            ): void {
                throw new HttpException(
                    'Access denied: insufficient role privileges.'
                );
            },
            ['admin'],
            Session::GUARD_ANY
        );
    }

    #[Route('/admin/dashboard', methods: ['GET'])]
    public function dashboard(): int
    {
        if (!$this->session->isOnline()) {
            $this->tpl->redirect('/admin/login');

            return STATUS_SILENT;
        }

        return $this->view('dashboard');
    }

    /**
     * Authenticate an administrator and establish a session.
     *
     * When strict session IP validation is enabled, login() binds the
     * session to the client's current IP address. The application-wide
     * onIpChanged() listener then detects a changed IP on subsequent
     * requests and logs the session out.
     */
    #[Route('/admin/login', methods: ['POST'])]
    public function loginAction(): int
    {
        $session = $this->app->session;

        // An authenticated session is already valid.
        if ($session->isOnline()) {
            if (!$session->isIpMatch()) {
                $session->logout();
            } else {
                return $this->send(['success' => true]);
            }
        }

        // Prevent repeated authentication attempts.
        if ($session->isLoginLocked(seconds: 300, maxAttempts: 5)) {
            return response()->json([
                'success' => false,
                'error'   => 'Too many failed attempts. Try again in a few minutes.',
            ]);
        }

        $username = $this->request->getPost('username');
        $password = $this->request->getPost('password');

        if (!$this->auth->attempt($username, $password)) {
            $session->attempt();

            return $this->send([
                'success'          => false,
                'error'            => 'Invalid credentials.',
                'attempts_remaining' => max(
                    0,
                    5 - $session->attempts()
                ),
            ]);
        }

        // Authentication succeeded. Reset failed attempts and establish
        // the authenticated session with the user's roles.
        $session
            ->attempt(reset: true)
            ->set('username', $username)
            ->set('email', $this->auth->user()->email)
            ->setRoles($this->auth->user()->roles)
            ->login();

        // Prevent session fixation after successful authentication.
        $session->regenerate(clearSessionData: false);

        return $this->send(['success' => true]);
    }

    #[Route('/admin/logout', methods: ['POST'])]
    public function logoutAction(): int
    {
        $this->app->session->logout();

        return $this->send(['success' => true]);
    }
}