Primordyx Framework Documentation

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
since
1.0.0

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 for storing the safe session ID

protected mixed COOKIE_NAME = 'primordyx_safe'
Tags
since
1.0.0

DEFAULT_LIFETIME

Default session lifetime in seconds (2 hours)

protected mixed DEFAULT_LIFETIME = 7200
Tags
since
1.0.0

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
since
1.0.0

$data

In-memory session data array

protected static array<string|int, mixed> $data = []
Tags
since
1.0.0

$dirty

Whether session data has been modified since last save

protected static bool $dirty = false
Tags
since
1.0.0

$lifetime

Session lifetime in seconds

protected static int $lifetime = self::DEFAULT_LIFETIME
Tags
since
1.0.0

$persistence

Database persistence implementation for session storage

protected static SafePersistenceInterface|null $persistence = null
Tags
since
1.0.0

$safeId

Current cryptographically secure session ID

protected static string|null $safeId = null
Tags
since
1.0.0

$started

Whether the session system has been initialized

protected static bool $started = false
Tags
since
1.0.0

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
throws
Exception

If session cannot be started

since
1.0.0
example
$allData = Safe::all();
foreach ($allData as $key => $value) {
    echo "$key: $value\n";
}
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
since
1.0.0

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
since
1.0.0
example
// In maintenance script
$cleaned = Safe::cleanup();
echo "Removed $cleaned expired sessions";
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
throws
Exception

If session cannot be started

since
1.0.0
example
// Clear all session data but keep session active
Safe::clear();

// Session ID remains the same, but all data is gone
$isEmpty = empty(Safe::all()); // true

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
since
1.0.0
example
// Configure for subdomain sharing
Safe::configureCookies([
    'domain' => '.example.com',
    'path' => '/',
    'secure' => true
]);
Safe::start();

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
since
1.0.0
example
// Complete logout process
Safe::destroy();
header('Location: /login');
exit;
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
throws
Exception

If session storage fails

since
1.0.0
example
// Set flash messages
Safe::flash('success', 'Data saved successfully!');
Safe::flash('error', 'Invalid input provided');
Safe::flash('user_data', ['id' => 123, 'name' => 'John']);

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
throws
Exception

If session cannot be started

since
1.0.0
example
Safe::forget('user_id');
Safe::forget('temp_data');

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
throws
Exception

If session cannot be started

since
1.0.0
example
$userId = Safe::get('user_id');
$userName = Safe::get('user_name', 'Guest');
$preferences = Safe::get('settings', []);
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
throws
Exception

If session operations fail

since
1.0.0
example
// Display flash message if it exists
$message = Safe::getFlash('success');
if ($message) {
    echo "<div class='alert-success'>$message</div>";
}

// Second call returns null (already consumed)
$gone = Safe::getFlash('success'); // null
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
since
1.0.0
example
$sessionId = Safe::getId();
error_log("Current session: $sessionId");
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
since
1.0.0
example
$lifetime = Safe::getLifetime();
echo "Sessions expire after " . ($lifetime / 3600) . " hours";
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
throws
Exception

If session cannot be started

since
1.0.0
example
if (Safe::has('user_id')) {
    $user = Safe::get('user_id');
}

// Distinguish between missing and null
Safe::set('flag', null);
Safe::has('flag');        // true (exists but null)
Safe::has('missing');     // false (doesn't exist)
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
since
1.0.0
example
if (!Safe::isStarted()) {
    Safe::start();
}
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
throws
Exception

If session operations fail

since
1.0.0
example
// Keep single flash message
Safe::reflash('error');

// Keep multiple flash messages
Safe::reflash(['error', 'warning', 'info']);

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
throws
RandomException

If secure random number generation fails

since
1.0.0
example
// Regenerate after login to prevent session fixation
if (authenticateUser($username, $password)) {
    Safe::regenerate();
    Safe::set('user_id', $user->id);
}
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
since
1.0.0
example
Safe::set('user_id', 123);
if (Safe::save()) {
    echo "Session saved successfully";
}
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
throws
Exception

If session cannot be started or storage fails

since
1.0.0
example
Safe::set('user_id', 123);
Safe::set('user_data', ['name' => 'John', 'email' => 'john@example.com']);
Safe::set('login_time', time());

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
since
1.0.0
example
// Set 4-hour session lifetime
Safe::setLifetime(14400);
Safe::start();

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

  1. Attempts to restore existing session from cookie
  2. Validates session against database persistence layer
  3. Creates new session if none exists or session expired
  4. Sets secure cookie with session ID
  5. 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
throws
Exception

If session operations fail

since
1.0.0
example

Basic Usage

// Start with defaults
Safe::start();

// Custom lifetime (1 hour)
Safe::start(null, 3600);

// Custom cookie settings
Safe::start(null, null, ['domain' => '.example.com']);
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
since
1.0.0
example
// Extend session during long operations
if (Safe::touch()) {
    performLongRunningTask();
}
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
since
1.0.0

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
throws
RandomException

If secure random number generation fails

since
1.0.0
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
throws
RuntimeException

If session cannot be started

throws
Exception

If session startup operations fail

since
1.0.0

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
throws
RandomException

If secure random number generation fails

since
1.0.0
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.

Tags
since
1.0.0

        
On this page

Search results