PHP Luminova: Handling User Login and Session Data
Store session data, establish login state after authentication, and check access to protected pages.
Luminova’s Session Handling class preserves visitor data across requests. It stores preferences such as the user data, and also manages user sign-in state and access-level roles that controllers can authenticate before granting access to protected pages and resources.
Start the session before sending response output so Luminova can resume the visitor’s existing session or open a new one.
Storage Managers
Luminova\Sessions\Managers\SessionManager uses PHP sessions and is the default. Luminova\Sessions\Managers\CookieManager stores session data on the client. Use the default manager for the login workflow below. See the session configuration guide for cookie settings and strict IP checks. Configure the storage namespace with App\Config\Session::$namespace and select an application storage with setStorage().
Session Handlers
Use a PHP session handler with SessionManager. SessionDatabaseHandler stores data in a database. SessionFileHandler writes session files. Luminova\Sessions\Handlers\SessionArrayHandler keeps data in memory for the current handler instance.
Custom Handlers
Extend AbstractSessionHandler to implement application-specific storage.
Start a session
Example
Start a session with the default PHP session manager.
use Luminova\Sessions\Session;
use Luminova\Sessions\Managers\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\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\SessionDatabaseHandler;
$session = new Session();
$session->setHandler(
new SessionDatabaseHandler('sessions')
);
$session->start();Class Definition
- Full namespace:
Luminova\Sessions\Session - This class implements Luminova\Interface\SessionInterface and Luminova\Interface\LazyObjectInterface.
- This class is an ordinary class.
Class Constants
| Constant | Value | Description |
|---|---|---|
GUARD_ANY | 0 | At least one required role must exist in the user's roles. |
GUARD_ALL | 1 | All required roles must be present in the user's roles (extras allowed). |
GUARD_EXACT | 2 | Exact match — all and only the specified roles must exist. |
GUARD_NONE | 3 | None of the given roles should be present (e.g., guest access only). |
DISABLED | 0 | Sessions are disabled. |
NONE | 1 | Sessions are enabled, but no session currently exists. |
ACTIVE | 2 | A session is currently active. |
Methods
__construct
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 function __construct(
private SessionManagerInterface $manager = new SessionManager(),
private SessionConfig $config = new SessionConfig()
)Parameters:
| Parameter | Type | Description |
|---|---|---|
$manager | SessionManagerInterface | Optional. A custom session manager instance (default: Luminova\Sessions\Managers\SessionManager). |
$config | App\Config\Session | Optional. 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 function getInstance(
?SessionManagerInterface $manager = null,
?SessionConfig $config = null
): staticParameters:
| Parameter | Type | Description |
|---|---|---|
$manager | SessionManagerInterface|null | Optional. A custom session manager instance. Used when the singleton is first initialized (default: null). |
$config | App\Config\Session|null | Optional. A custom session configuration. Used when the singleton is first initialized (default: null). |
Return:
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 function from(
string $storage,
?SessionManagerInterface $manager = null,
?SessionConfig $config = null
): staticParameters:
| Parameter | Type | Description |
|---|---|---|
$storage | string | The session storage name. |
$manager | SessionManagerInterface|null | Optional session manager (default: Luminova\Sessions\Managers\SessionManager). |
$config | App\Config\Session|null | Optional session configuration (default: App\Config\Session). |
Return:
static - Return a new Session instance configured for the specified storage.
Examples:
$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:
4bits: hexadecimal characters[0-9a-f]5bits: base32-like characters[0-9a-v]6bits: extended base64-like character set
public static function toSessionId(string $input, string $algo = 'sha256'): ?stringParameters:
| Parameter | Type | Description |
|---|---|---|
$input | string | The input string to convert. |
$algo | string | The hashing algorithm to use if the input is not already a 64-character hex hash (default: sha256). |
Return:
string|null - Return the generated session ID, or null on failure.
Throws:
- Luminova\Exceptions\RuntimeException - If
session.sid_bits_per_characteris unsupported.
Examples:
Convert a CLI system ID to a PHP session ID:
$sid = Session::toSessionId(Luminova\Command\Terminal::getSystemId());Convert an application-controlled identifier for a CLI workflow. Use PHP-generated IDs for browser login sessions:
$sid = Session::toSessionId('local-cli-worker');getManager
Retrieves the current session storage manager instance.
This method returns the session manager instance responsible for handling session data, either Luminova\Sessions\Managers\CookieManager or Luminova\Sessions\Managers\SessionManager.
public function getManager(): ?SessionManagerInterfaceReturn:
SessionManagerInterface|null - Return the current session manager instance, or null if not set.
getStorage
Retrieves the current session storage name.
public function getStorage(): stringReturn:
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 function getName(): stringReturn:
string - Return the session cookie name.
getResult
Retrieves all session data in the specified format.
public function getResult(bool $asObject = false): array|objectParameters:
| Parameter | Type | Description |
|---|---|---|
$asObject | bool | If true, return the data as an object, otherwise as an array (default: false). |
Return:
array<array-key, mixed>|object - Return the stored session data in the requested format.
get
Retrieves a value from the session storage.
public function get(string $name, mixed $default = null): mixedParameters:
| Parameter | Type | Description |
|---|---|---|
$name | string | The session data key. |
$default | mixed | The default value returned if the key does not exist. |
Return:
mixed - Returns the retrieved session data or the default value if not found.
getId
Retrieves the active PHP session identifier.
public function getId(): ?stringReturn:
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 function getIp(): ?stringReturn:
string|null - Return the stored IP address, or null if not set.
getUserAgent
Retrieves the user agent associated with the login session.
public function getUserAgent(): ?stringReturn:
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 function getToken(): ?stringReturn:
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 function getDatetime(): ?stringReturn:
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 function getTimestamp(): intReturn:
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 function getExpiration(): intReturn:
int - Return the expiration timestamp.
getUpdatedAt
Retrieves the timestamp of the last session update.
public function getUpdatedAt(): ?intReturn:
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 function getLastAttempt(): ?intReturn:
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 function getMeta(string $name): mixedParameters:
| Parameter | Type | Description |
|---|---|---|
$name | string | The metadata key to retrieve. |
Return:
mixed - Return the metadata value, or null if it does not exist.
getMetadata
Retrieves all session login metadata.
public function getMetadata(): arrayReturn:
array<string,mixed> - Returns the recorded login metadata. Fields appear as the corresponding state is recorded.
| Key | Type | Description |
|---|---|---|
online | string | Login marker. The value is 'on' after login. |
timestamp | int | Login time as a Unix timestamp. |
updated_at | int | Last recorded activity timestamp. |
agent | string | Recorded user agent. |
token | string | Login metadata token. |
ip | string | Bound IP address when strict IP checking is enabled. |
ip_changes | array<int,string> | Recorded IP address changes. |
attempts | int | Recorded failed login attempts. |
attempted_at | int\|null | Timestamp of the last recorded attempt. |
attempt_times | array<int,float> | High-resolution attempt timestamps. |
roles | array<int,string\|int> | Roles assigned to the session. |
getAttributes
Retrieves all session user data, excluding internal login metadata.
public function getAttributes(): arrayReturn:
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 function getIpAddresses(): arrayReturn:
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 function getAttemptTimes(): arrayReturn:
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 function getRoles(): arrayReturn:
array<int,string|int> - Return a list of assigned roles, or an empty array if none.
Examples:
$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\SessionDatabaseHandler: Stores session data in a database.Luminova\Sessions\Handlers\SessionFileHandler: Saves session data in files.Luminova\Sessions\Handlers\SessionArrayHandler: Stores session data temporarily in an array.
public function setHandler(AbstractSessionHandler $handler): selfParameters:
| Parameter | Type | Description |
|---|---|---|
$handler | Luminova\Base\AbstractSessionHandler | The session save handler instance. |
Return:
self - Returns the instance of session class.
Reference
For more details on session handlers, refer to the following documentation:
- Database Session Handler – Stores session data in a database for persistent storage.
- Filesystem Session Handler – Saves session data in files on the server.
- Abstract Base Session Handler – Provides a common interface for custom session handlers.
Examples:
Using the database handler:
use Luminova\Sessions\Handlers\SessionDatabaseHandler;
$session->setHandler(new SessionDatabaseHandler('sessions'));Using the filesystem handler:
use Luminova\Sessions\Handlers\SessionFileHandler;
$session->setHandler(new SessionFileHandler());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\SessionManager, this method allows specifying a session manager to determine where session data is stored.
The session manager can be either:
Luminova\Sessions\Managers\CookieManager: Stores session data in client-side cookies.Luminova\Sessions\Managers\SessionManager: Uses PHP's default$_SESSIONstorage.
public function setManager(SessionManagerInterface $manager): selfParameters:
| Parameter | Type | Description |
|---|---|---|
$manager | SessionManagerInterface | The session manager instance to set. |
Return:
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 function setStorage(string $storage): selfParameters:
| Parameter | Type | Description |
|---|---|---|
$storage | string | The session storage name to set. |
Return:
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 function setNamespace(?string $table): selfParameters:
| Parameter | Type | Description |
|---|---|---|
$table | string|null | The namespace, or null to use default. |
Return:
self - Returns the instance of session class.
Throws:
- Luminova\Exceptions\InvalidArgumentException - If the namespace is invalid.
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 function set(string $name, mixed $value): selfParameters:
| Parameter | Type | Description |
|---|---|---|
$name | string | The key to identify the session data. |
$value | mixed | The value to associate with the specified key. |
Return:
self - Returns the instance of session class.
Throws:
- Luminova\Exceptions\RuntimeException - If the session has not been started.
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 function add(string $name, mixed $value, bool &$status = false): selfParameters:
| Parameter | Type | Description |
|---|---|---|
$name | string | The key to identify the session data. |
$value | mixed | The value to associate with the specified key. |
$status | bool | A reference variable indicating whether the value was added (true) or already existed (false). |
Return:
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 function put(string $name, mixed $value): selfParameters:
| Parameter | Type | Description |
|---|---|---|
$name | string | The key to identify the session data. |
$value | mixed | The value to associate with the specified key. |
Return:
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 function save(): boolReturn:
bool - Return true if the queued data was successfully saved, otherwise false when there was nothing to save.
Throws:
- Luminova\Exceptions\RuntimeException - If the session has not been started.
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 function all(): arrayReturn:
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 function touch(?int $timestamp = null): selfParameters:
| Parameter | Type | Description |
|---|---|---|
$timestamp | int|null | Optional Unix timestamp to record (default: current time). |
Return:
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 function close(): boolReturn:
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 function dequeue(): boolReturn:
bool - Returns true.
is
Checks whether the current session or cookie status matches the given status.
public function is(int $status = self::ACTIVE): boolParameters:
| Parameter | Type | Description |
|---|---|---|
$status | int | The 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:
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 function isStarted(): boolReturn:
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 function isOnline(): boolReturn:
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 function isExpired(int $seconds = 3600): boolParameters:
| Parameter | Type | Description |
|---|---|---|
$seconds | int | The time threshold in seconds before the session is considered expired (default: 3600). |
Return:
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 function isIpLocked(): boolReturn:
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 function isStrictMode(): boolReturn:
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 function isIpMatch(): boolReturn:
bool - Returns true if the session IP is valid, otherwise false.
isIdleFor
Determines whether the session has been inactive for the specified duration.
public function isIdleFor(int $seconds): boolParameters:
| Parameter | Type | Description |
|---|---|---|
$seconds | int | Minimum number of seconds since the last activity. |
Return:
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 function isLoginLocked(
int $seconds = 300,
int $maxAttempts = 3
): boolParameters:
| Parameter | Type | Description |
|---|---|---|
$seconds | int | Number of seconds the login remains locked after the maximum attempt count is reached (default: 300). |
$maxAttempts | int | Maximum number of failed login attempts allowed before the session is locked (default: 3). |
Return:
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 function isRapidAttempts(
int $window = 10,
int $maxAttempts = 5
): boolParameters:
| Parameter | Type | Description |
|---|---|---|
$window | int | Time window in seconds (default: 10). |
$maxAttempts | int | Maximum allowed attempts within the window (default: 5). |
Return:
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 function useStrictMode(bool $enable = true): selfParameters:
| Parameter | Type | Description |
|---|---|---|
$enable | bool | Whether to enable strict session ID validation (default: true). |
Return:
self - Returns the instance of session class.
toArray
Retrieves session data as an associative array.
public function toArray(?string $name = null): arrayParameters:
| Parameter | Type | Description |
|---|---|---|
$name | string|null | Optional name to retrieve specific data. If null, returns all session data. |
Return:
array<string,mixed> - Return the session data as an associative array.
toObject
Retrieves session data as an object.
public function toObject(?string $name = null): objectParameters:
| Parameter | Type | Description |
|---|---|---|
$name | string|null | Optional name to retrieve specific data. If null, returns all session data. |
Return:
object - Return the session data as a standard object.
remove
Removes an item from the session storage by key.
public function remove(string $name): selfParameters:
| Parameter | Type | Description |
|---|---|---|
$name | string | The item name to remove. |
Return:
self - Returns the instance of session class.
Throws:
- Luminova\Exceptions\RuntimeException - If an operation is attempted without an active session.
clear
Clears all data from the current session storage.
public function clear(): selfReturn:
self - Returns the instance of session class.
Throws:
- Luminova\Exceptions\RuntimeException - If an operation is attempted without an active session.
has
Checks whether an item key exists in the session storage.
public function has(string $name): boolParameters:
| Parameter | Type | Description |
|---|---|---|
$name | string | The item name to check. |
Return:
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 function attempt(bool $reset = false): boolParameters:
| Parameter | Type | Description |
|---|---|---|
$reset | bool | If true, resets the attempt count to zero. |
Return:
bool - Returns true.
See Also: isLoginLocked()
attempts
Retrieves the number of recorded session login attempts.
public function attempts(): intReturn:
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 function regenerate(bool $clearSessionData = false): string|boolParameters:
| Parameter | Type | Description |
|---|---|---|
$clearSessionData | bool | Whether to delete the data associated with the previous identifier (default: false). |
Return:
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 function setRoles(array $roles): selfParameters:
| Parameter | Type | Description |
|---|---|---|
$roles | array<int,string\|int> | Roles to assign to the session user. |
Return:
self - Returns the instance of session class.
Throws:
- Luminova\Exceptions\InvalidArgumentException - If the roles are not a valid indexed list.
See Also: assignRoles(), inRoles(), getRoles()
Examples:
$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 function assignRoles(array $roles): selfParameters:
| Parameter | Type | Description |
|---|---|---|
$roles | array<int,string\|int> | Roles to add to the session user. |
Return:
self - Returns the instance of session class.
Throws:
- Luminova\Exceptions\InvalidArgumentException - If the roles are not a valid indexed list.
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 function revokeRoles(array $roles): selfParameters:
| Parameter | Type | Description |
|---|---|---|
$roles | array<int,string\|int> | Roles to revoke from the session user. |
Return:
self - Returns the instance of session class.
Throws:
- Luminova\Exceptions\InvalidArgumentException - If the roles are not a valid indexed list.
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 function inRoles(?array $roles = null, int $mode = self::GUARD_ANY): boolParameters:
| Parameter | Type | Description |
|---|---|---|
$roles | array<int,string\|int>\|null | Roles to check against the current user. Defaults to the roles set via setRoles(). |
$mode | int | Role matching mode (default: Session::GUARD_ANY). |
Return:
bool - Returns true if the user satisfies the role requirements, otherwise false.
Throws:
- Luminova\Exceptions\InvalidArgumentException - If the role list is invalid or the matching mode is not supported.
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 function onRoleGuard(
callable $onDenied,
?array $roles = null,
int $mode = 0
): voidParameters:
| Parameter | Type | Description |
|---|---|---|
$onDenied | callable | Receives the session, the required roles, and the assigned roles when authorization fails. |
$roles | array<int,string\|int>\|null | Roles required for authorization. Defaults to the roles set via setRoles(). |
$mode | int | Role matching mode. One of Session::GUARD_* (default: Session::GUARD_ANY). |
Return:
void - Registers the callback for a subsequent session start.
See Also: setRoles(), inRoles()
Examples:
$session->onRoleGuard(
function (Session $session, array $expected, array $subscriptions): void {
throw new \Luminova\Exceptions\HttpException('Access denied.', 403);
},
['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 function onIpChanged(callable $onChange): selfParameters:
| Parameter | Type | Description |
|---|---|---|
$onChange | callable | Callback invoked when the session IP address changes. Receives the session instance, the previous IP address, and the recorded IP changes. |
Return:
self - Returns the instance of session class.
Examples:
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 function start(?string $sessionId = null): boolParameters:
| Parameter | Type | Description |
|---|---|---|
$sessionId | string|null | Optional session ID to resume when starting the session. |
Return:
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.
Examples:
Starting a session with a specified session ID:
namespace App;
use Luminova\Foundation\Core\AbstractApplication 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 function login(?string $ip = null): boolParameters:
| Parameter | Type | Description |
|---|---|---|
$ip | string|null | Optional 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:
bool - Returns true if the login session was successfully started, otherwise false.
Throws:
- Luminova\Exceptions\LogicException - If strict IP validation is disabled and an IP address is provided.
Examples:
After your application verifies the user’s credentials, assign their roles, call login() to record the sign-in, and rotate the session ID with regenerate().
$session->set('user_id', $account->id);
$session->setRoles($account->roles);
if (!$session->login() || $session->regenerate() === false) {
$session->logout();
throw new RuntimeException(
'Could not establish the login session.'
);
}On a later request to an admin dashboard, use
isOnline()to check whether the visitor is signed in andinRoles(['admin'])to check whether they can access the page.
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 function logout(): boolReturn:
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 function destroy(): boolReturn:
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 function destroyNative(): boolReturn:
bool - Return true if the session and cookie were successfully destroyed, otherwise false.
setSessionSavePath
Configure the directory PHP uses for session storage. Call this before a session starts. The method creates the directory if it is missing.
public static function setSessionSavePath(string $path, int $dirPermissions = 0700): boolParameters:
| Parameter | Type | Description |
|---|---|---|
$path | string | Session save directory outside the public document root. |
$dirPermissions | int | Permission bits used when creating the directory (default: 0700). |
Return:
bool - Returns true when PHP accepts the save path, or false when the path is empty.
Throws:
- Luminova\Exceptions\InvalidArgumentException If the permission bits are invalid.
- Luminova\Exceptions\RuntimeException If the directory cannot be created, is unwritable, or PHP rejects the save path.
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 function configure(object|array $config): boolParameters:
| Parameter | Type | Description |
|---|---|---|
$config | object\|array<string,mixed> | Session configuration. |
Return:
bool - Return true if the configuration was applied, otherwise false.
Throws:
- Luminova\Exceptions\RuntimeException - If the configured save path is invalid or not writable, or if session cookie parameters cannot be configured.
Examples:
use App\Config\Session as SessionConfig;
use Luminova\Sessions\Session;
Session::configure(new SessionConfig());
session_start();restartIfNeeded
Ensures the session is started.
Returns immediately when the session is already active; otherwise, attempts to start the session.
public function restartIfNeeded(): boolReturn:
bool - Returns true if the session is already active or was successfully started, otherwise false.
Access session values
Use get(), set(), and has() to read, write, and check named values. PHP property syntax is also available for those operations.
$session->theme = 'dark';
if (isset($session->theme)) {
echo $session->theme;
}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 check: the controller checks the stored roles before rendering a protected page.
- Login flow: verifies credentials, assigns roles, and rotates the session ID. The session attempt counter tracks failures for the current session.
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\AbstractApplication as CoreApplication;
use Luminova\Logger\Logger;
use Luminova\Sessions\Session;
class Application extends CoreApplication
{
public ?Session $session = null;
protected function onCreate(): void
{
$this->session = Session::from('admin');
// Enable strictSessionIp in App\Config\Session to use this listener.
$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
This example uses an application model, App\Models\Users, with a findForLogin() method that returns an account ID, password hash, and array of roles. Include a CSRF token named csrf_token in the login and logout forms. Render an admin/dashboard view for authorized requests.
// app/Controllers/Http/AdminController.php
namespace App\Controllers\Http;
use App\Models\Users;
use Luminova\Attributes\Route;
use Luminova\Base\Http\AbstractController;
use Luminova\Security\CSRF;
use Luminova\Sessions\Session;
class AdminController extends AbstractController
{
#[Route('/admin/dashboard', methods: ['GET'])]
public function dashboard(): int
{
$session = $this->app->session;
if (!$session->isOnline()) {
return $this->send(['error' => 'Sign in first.'], status: 401);
}
if (!$session->inRoles(['admin'], Session::GUARD_ANY)) {
return $this->send(['error' => 'Access denied.'], status: 403);
}
return $this->view('admin/dashboard');
}
#[Route('/admin/login', methods: ['POST'])]
public function loginAction(): int
{
$session = $this->app->session;
if (!$session->isStarted()) {
return $this->send(['error' => 'Session unavailable.'], status: 503);
}
if (!CSRF::validate((string) $this->request->getPost('csrf_token', ''))) {
return $this->send(['error' => 'Invalid form token.'], status: 403);
}
if ($session->isOnline()) {
return $this->send(['success' => true]);
}
if ($session->isLoginLocked(seconds: 300, maxAttempts: 5)) {
return $this->send(['error' => 'Try again later.'], status: 429);
}
$username = (string) $this->request->getPost('username', '');
$password = (string) $this->request->getPost('password', '');
$account = (new Users())->findForLogin($username);
if (!$account || !password_verify($password, $account->passwordHash)) {
$session->attempt();
return $this->send(['error' => 'Invalid credentials.'], status: 401);
}
$session->set('user_id', $account->id)->setRoles($account->roles);
if (!$session->login() || $session->regenerate() === false) {
$session->destroy();
return $this->send(['error' => 'Could not establish the session.'], status: 500);
}
return $this->send(['success' => true]);
}
#[Route('/admin/logout', methods: ['POST'])]
public function logoutAction(): int
{
if (!CSRF::validate((string) $this->request->getPost('csrf_token', ''))) {
return $this->send(['error' => 'Invalid form token.'], status: 403);
}
if (!$this->app->session->destroy()) {
return $this->send(['error' => 'Could not close the session.'], status: 500);
}
return $this->send(['success' => true]);
}
}