Safe
in package
Secure Database-Backed Session Management System
Provides a secure, database-backed replacement for PHP's built-in $_SESSION system with automatic expiration, cryptographic security, and comprehensive session lifecycle management. Designed for applications requiring enhanced security, audit trails, and distributed session storage.
Key Features
- Database Storage: Sessions stored in database instead of files for scalability
- Cryptographic Security: Secure ID generation using cryptographically secure random bytes
- Automatic Expiration: Configurable session lifetime with automatic cleanup
- Flash Messaging: Built-in flash message support for user notifications
- Cookie Security: Secure cookie handling with configurable security attributes
- Development Mode: Automatic HTTP/HTTPS detection for development environments
Security Architecture
- Uses 64-character cryptographically secure session IDs
- Secure cookie defaults (HttpOnly, Secure, SameSite=Strict)
- Session regeneration support to prevent session fixation attacks
- Automatic cleanup of expired sessions to prevent database bloat
- No session data stored in cookies - only secure session ID
Usage Patterns
// Initialize session system
Safe::start();
// Store and retrieve data
Safe::set('user_id', 123);
$userId = Safe::get('user_id');
// Flash messages
Safe::flash('success', 'Data saved successfully');
$message = Safe::getFlash('success');
// Security operations
Safe::regenerate(); // Prevent session fixation
Safe::destroy(); // Complete logout
Tags
Table of Contents
Constants
- COOKIE_NAME = 'primordyx_safe'
- Cookie name for storing the safe session ID
- DEFAULT_LIFETIME = 7200
- Default session lifetime in seconds (2 hours)
Properties
- $cookieSettings : array<string|int, mixed>
- Security-focused cookie configuration settings
- $data : array<string|int, mixed>
- In-memory session data array
- $dirty : bool
- Whether session data has been modified since last save
- $lifetime : int
- Session lifetime in seconds
- $persistence : SafePersistenceInterface|null
- Database persistence implementation for session storage
- $safeId : string|null
- Current cryptographically secure session ID
- $started : bool
- Whether the session system has been initialized
Methods
- all() : array<string|int, mixed>
- Retrieve all session data as associative array
- autoSave() : void
- Automatic save handler called on script shutdown
- cleanup() : int
- Remove expired sessions from database storage
- clear() : void
- Remove all data from the secure session
- configureCookies() : void
- Configure cookie security settings
- destroy() : bool
- Completely destroy the session and remove all traces
- flash() : void
- Store flash data that persists for exactly one request
- forget() : void
- Remove a key from the secure session
- get() : mixed
- Retrieve a value from the secure session
- getFlash() : mixed
- Retrieve and consume flash data (auto-removes after retrieval)
- getId() : string|null
- Get the current session ID for debugging or logging purposes
- getLifetime() : int
- Get current session lifetime configuration
- has() : bool
- Check if a key exists in the secure session
- isStarted() : bool
- Check if session system has been initialized
- reflash() : void
- Keep flash data for another request cycle
- regenerate() : bool
- Regenerate session ID for security (prevents session fixation attacks)
- save() : bool
- Persist current session data to database storage
- set() : void
- Store a value in the secure session
- setLifetime() : void
- Configure session lifetime in seconds
- start() : bool
- Initialize the secure session system with database persistence
- touch() : bool
- Extend session expiration without modifying data
- clearCookie() : void
- Clear session cookie by setting expired timestamp
- createNew() : bool
- Create new session with cryptographically secure ID
- ensureStarted() : void
- Ensure session is started or throw exception
- generateSafeId() : string
- Generate cryptographically secure 64-character session ID
- setCookie() : void
- Set secure session cookie with configured security attributes
Constants
COOKIE_NAME
Cookie name for storing the safe session ID
protected
mixed
COOKIE_NAME
= 'primordyx_safe'
Tags
DEFAULT_LIFETIME
Default session lifetime in seconds (2 hours)
protected
mixed
DEFAULT_LIFETIME
= 7200
Tags
Properties
$cookieSettings
Security-focused cookie configuration settings
protected
static array<string|int, mixed>
$cookieSettings
= [
'httponly' => true,
'secure' => true,
// Always secure by default
'samesite' => 'Strict',
// Strict for maximum security
'path' => '/',
'domain' => '',
]
Tags
$data
In-memory session data array
protected
static array<string|int, mixed>
$data
= []
Tags
$dirty
Whether session data has been modified since last save
protected
static bool
$dirty
= false
Tags
$lifetime
Session lifetime in seconds
protected
static int
$lifetime
= self::DEFAULT_LIFETIME
Tags
$persistence
Database persistence implementation for session storage
protected
static SafePersistenceInterface|null
$persistence
= null
Tags
$safeId
Current cryptographically secure session ID
protected
static string|null
$safeId
= null
Tags
$started
Whether the session system has been initialized
protected
static bool
$started
= false
Tags
Methods
all()
Retrieve all session data as associative array
public
static all() : array<string|int, mixed>
Returns complete copy of current session data including flash messages and any temporary data stored in the session.
Tags
Return values
array<string|int, mixed> —Complete session data array
autoSave()
Automatic save handler called on script shutdown
public
static autoSave() : void
Ensures session data is persisted even if save() is not explicitly called. Registered automatically as shutdown function to prevent data loss from unexpected script termination or developer oversight.
Tags
cleanup()
Remove expired sessions from database storage
public
static cleanup() : int
Performs maintenance by deleting expired session records from the database. Should be called periodically via cron job or application maintenance routines to prevent database bloat from abandoned sessions.
Tags
Return values
int —Number of expired sessions removed
clear()
Remove all data from the secure session
public
static clear() : void
Clears all session data while maintaining the session ID and cookie. Useful for partial logout scenarios or session reset operations.
Tags
configureCookies()
Configure cookie security settings
public
static configureCookies(array<string|int, mixed> $settings) : void
Merges provided settings with secure defaults for session cookie attributes. Must be called before start() to affect cookie creation. Supports all standard cookie attributes for fine-tuned security control.
Parameters
- $settings : array<string|int, mixed>
-
Cookie configuration array (path, domain, secure, httponly, samesite)
Tags
destroy()
Completely destroy the session and remove all traces
public
static destroy() : bool
Removes session from database, clears cookie, and resets all internal state. Used for complete logout scenarios where no session data should remain.
Tags
Return values
bool —True if destroyed successfully, false on database errors
flash()
Store flash data that persists for exactly one request
public
static flash(string $key, mixed $value) : void
Flash data is automatically removed after being retrieved once, making it perfect for user notifications and temporary messages that should display exactly once after redirects.
Parameters
- $key : string
-
The flash key identifier
- $value : mixed
-
The flash value to store
Tags
forget()
Remove a key from the secure session
public
static forget(string $key) : void
Deletes the specified key and its value from session storage. Sets dirty flag if key existed to ensure persistence on save.
Parameters
- $key : string
-
The key to remove from session
Tags
get()
Retrieve a value from the secure session
public
static get(string $key[, mixed $default = null ]) : mixed
Returns stored session data with optional default value fallback. Automatically ensures session is started before attempting retrieval.
Parameters
- $key : string
-
The storage key to retrieve
- $default : mixed = null
-
Default value returned if key doesn't exist
Tags
Return values
mixed —The stored value or default value
getFlash()
Retrieve and consume flash data (auto-removes after retrieval)
public
static getFlash(string $key[, mixed $default = null ]) : mixed
Returns flash data and immediately removes it from session, ensuring flash messages display exactly once. Subsequent calls return default value.
Parameters
- $key : string
-
The flash key to retrieve
- $default : mixed = null
-
Default value if flash key doesn't exist
Tags
Return values
mixed —The flash value or default value
getId()
Get the current session ID for debugging or logging purposes
public
static getId() : string|null
Returns the cryptographically secure session identifier. Useful for debugging, logging, or advanced session management operations.
Tags
Return values
string|null —The current session ID or null if not started
getLifetime()
Get current session lifetime configuration
public
static getLifetime() : int
Returns the configured session lifetime in seconds. Useful for displaying session timeout warnings or calculating expiration timestamps.
Tags
Return values
int —Session lifetime in seconds
has()
Check if a key exists in the secure session
public
static has(string $key) : bool
Tests for key existence using array_key_exists to distinguish between non-existent keys and keys with null values.
Parameters
- $key : string
-
The key to check for existence
Tags
Return values
bool —True if key exists (even with null value), false otherwise
isStarted()
Check if session system has been initialized
public
static isStarted() : bool
Returns session state without triggering initialization. Useful for conditional session operations or debugging session lifecycle issues.
Tags
Return values
bool —True if session is active, false otherwise
reflash()
Keep flash data for another request cycle
public
static reflash(string|array<string|int, mixed> $keys) : void
Prevents flash data from being consumed, allowing it to persist for one additional request. Useful when validation fails and you need to redisplay the same flash messages.
Parameters
- $keys : string|array<string|int, mixed>
-
Single key or array of keys to preserve
Tags
regenerate()
Regenerate session ID for security (prevents session fixation attacks)
public
static regenerate() : bool
Creates new cryptographically secure session ID while preserving all session data. Essential security practice after privilege changes or authentication. Deletes old session from database and updates cookie with new ID.
Tags
Return values
bool —True if regeneration successful, false on failure
save()
Persist current session data to database storage
public
static save() : bool
Saves modified session data to database if changes exist. No-op if session is unchanged. Automatically called on script shutdown via autoSave().
Tags
Return values
bool —True if saved successfully or no changes exist, false on failure
set()
Store a value in the secure session
public
static set(string $key, mixed $value) : void
Stores any serializable data in the session with automatic dirty flag management. Data is kept in memory until save() is called or automatic save occurs on shutdown.
Parameters
- $key : string
-
The storage key identifier
- $value : mixed
-
The value to store (must be serializable)
Tags
setLifetime()
Configure session lifetime in seconds
public
static setLifetime(int $seconds) : void
Sets the duration that sessions remain valid before automatic expiration. Affects new sessions and session extension operations. Must be called before start() to affect initial session creation.
Parameters
- $seconds : int
-
Session lifetime in seconds
Tags
start()
Initialize the secure session system with database persistence
public
static start([SafePersistenceInterface|null $persistence = null ][, int|null $lifetime = null ][, array<string|int, mixed> $cookieSettings = [] ]) : bool
Starts or resumes a secure session using database storage instead of PHP's default file-based sessions. Handles session creation, existing session restoration, cookie security configuration, and automatic HTTP/HTTPS environment detection.
Security Features
- Cryptographically secure 64-character session IDs
- Secure cookie defaults (HttpOnly, Secure, SameSite=Strict)
- Automatic HTTP detection for development environments
- Session expiration and automatic cleanup support
Session Lifecycle
- Attempts to restore existing session from cookie
- Validates session against database persistence layer
- Creates new session if none exists or session expired
- Sets secure cookie with session ID
- Extends session expiration on successful load
Parameters
- $persistence : SafePersistenceInterface|null = null
-
Custom persistence implementation (defaults to DatabaseSafePersistence)
- $lifetime : int|null = null
-
Session lifetime in seconds (defaults to DEFAULT_LIFETIME)
- $cookieSettings : array<string|int, mixed> = []
-
Cookie security configuration overrides
Tags
Return values
bool —True if session started successfully, false on failure
touch()
Extend session expiration without modifying data
public
static touch() : bool
Updates session expiration timestamp in database persistence layer to prevent session timeout during long user sessions or background operations.
Tags
Return values
bool —True if expiration updated successfully, false on failure
clearCookie()
Clear session cookie by setting expired timestamp
protected
static clearCookie() : void
Removes session cookie from client browser by setting expiration to past timestamp. Uses same cookie attributes as setCookie() to ensure proper cookie targeting and removal.
Tags
createNew()
Create new session with cryptographically secure ID
protected
static createNew() : bool
Generates secure session ID, initializes empty data storage, and creates database record with calculated expiration timestamp. Sets secure cookie and initializes internal session state.
Tags
Return values
bool —True if session created successfully, false on database errors
ensureStarted()
Ensure session is started or throw exception
protected
static ensureStarted() : void
Internal helper that guarantees session is initialized before data operations. Attempts to start session automatically and throws exception if startup fails. Prevents operations on uninitialized session state.
Tags
generateSafeId()
Generate cryptographically secure 64-character session ID
protected
static generateSafeId() : string
Uses random_bytes() with 32 bytes converted to hexadecimal for maximum entropy and security. Provides 256 bits of randomness to prevent session ID prediction or brute force attacks.
Tags
Return values
string —Cryptographically secure 64-character hexadecimal session ID
setCookie()
Set secure session cookie with configured security attributes
protected
static setCookie() : void
Creates HTTP cookie containing session ID with security-focused defaults. Applies configured cookie settings for path, domain, security flags, and SameSite protection. No-op if session ID is not available.