inanepain / session
A lightweight, secure and extensible PHP session handling library.
Installs: 0
Dependents: 0
Suggesters: 0
Security: 0
Stars: 0
Watchers: 0
Forks: 0
pkg:composer/inanepain/session
Requires
- php: >=8.4
- inanepain/datetime: *
- inanepain/stdlib: *
This package is auto-updated.
Last update: 2025-11-24 18:51:56 UTC
README
Table of Contents
inanepain/session- 1. Introduction
- 2. Install (Composer Recommended)
- 3. Quick Start
- 4. Configuration
- 5. API Reference
- 6. Examples
- 7. Security Considerations
inanepain/session
A lightweight, secure and extensible PHP session handling library.
1. Introduction
SessionManager is a lightweight, secure, and extensible PHP session handling library designed for modern web applications. It provides a simple static API for managing sessions with built-in security features like HTTP-only cookies, SameSite protection, periodic ID regeneration, and inactivity timeouts. It supports namespacing to avoid key collisions and "remember me" functionality for persistent sessions across browser closes.
Key features: * Automatic secure session initialization. * Namespaced storage to organize data (e.g., user, cart). * Flash messages for one-time notifications. * Configurable timeouts and regeneration intervals. * Memory-safe handling for large sessions. * Persistent sessions via "remember me" (30-day default).
This library is dependency-free, PSR-compliant, and production-ready.
1.1. Why SessionManager?
Native PHP sessions are powerful but lack secure defaults and organization.
SessionManager wraps session_* functions with best practices, preventing common pitfalls like fixation attacks and key conflicts.
2. Install (Composer Recommended)
Add to your composer.json:
$ composer require inanepain/session
3. Quick Start
3.1. Basic Usage
Require the file and initialize:
SessionManager::init([ 'name' => 'MYAPP_SESSID', // 'cookie_secure' => true, // HTTPS only 'cookie_samesite' => 'Strict', ]); // Set and get data SessionManager::set('user_id', 123); echo SessionManager::get('user_id'); // 123 // Flash message SessionManager::flash('success', 'Login successful!'); header('Location: /dashboard'); exit; // In dashboard.php if (SessionManager::hasFlash('success')) { echo SessionManager::getFlash('success'); } // Logout SessionManager::destroy();
3.2. Namespaced Sessions
Use the base class SessionNamespace for modular access:
class UserSession extends SessionNamespace { protected const NAMESPACE = 'user'; } class CartSession extends SessionNamespace { protected const NAMESPACE = 'cart'; } // Usage UserSession::set('id', 456); CartSession::set('items', ['item1']); echo UserSession::get('id'); // 456
4. Configuration
Pass options to init() to customize behaviour. Defaults are secure.
| Option | Type | Default | Description |
|---|---|---|---|
cookie_lifetime |
int |
0 |
Cookie expiry (0 = browser close; >0 for persistent). |
cookie_path |
string |
/ |
Cookie path. |
cookie_domain |
string |
'' |
Cookie domain. |
cookie_secure |
bool |
HTTPS detected |
HTTPS-only cookie. |
cookie_httponly |
bool |
true |
Prevent JS access. |
cookie_samesite |
string |
Lax |
CSRF protection (Lax/Strict/None). |
use_strict_mode |
bool |
true |
Reject uninit sessions. |
use_only_cookies |
bool |
true |
No URL param fallback. |
name |
string |
PHPSESSID |
Session cookie name. |
gc_maxlifetime |
int |
1440 |
Garbage collection (minutes). |
memory_limit |
string |
null |
Temp boost (e.g., '2G'; dev only). |
max_session_size |
int |
104857600 |
Clear if >100MB (bytes). |
force_clear |
bool |
false |
Nuke session on init (dev). |
remember_me |
bool |
false |
Auto-set lifetime to 30 days. |
Example with persistent session:
SessionManager::init([ 'remember_me' => true, // 30-day cookie // 'cookie_secure' => true, ]);
Runtime toggles:
SessionManager::enableRememberMe(86400 * 7); // 1 week SessionManager::disableRememberMe(); // Back to session-only echo SessionManager::isRememberMe() ? 'Persistent' : 'Temporary';
5. API Reference
All methods are static. Call init() first.
5.1. Initialization
Method |
Description |
|
Start session with config. Idempotent. |
5.2. Core Storage
Method |
Description |
|
Store value; updates activity. |
|
Retrieve value. |
|
Key exists? |
|
Remove key. |
|
All namespace data. |
|
Empty current namespace. |
5.3. Namespacing
Method |
Description |
|
Switch namespace. |
|
Active namespace. |
5.4. Flash Messages
Method |
Description |
|
Set for next request. |
|
Get and erase. |
|
Exists? (non-destructive). |
5.5. Security & Lifecycle
Method |
Description |
|
New ID; updates activity. |
|
Interval (min 60s). |
|
Inactivity timeout (min 1s). |
|
Full logout (clears data/cookie). |
|
Raw session ID. |
5.6. Remember Me
Method |
Description |
|
Enable persistent (regenerates ID). |
|
Disable (session-only). |
|
Currently persistent? |
6. Examples
6.1. Login with Remember Me
SessionManager::init(['remember_me' => $_POST['remember'] ?? false]); if (authenticate($_POST['email'], $_POST['password'])) { SessionManager::set('user_id', $user->id); SessionManager::enableRememberMe(); // If checkbox checked SessionManager::flash('success', 'Welcome!'); header('Location: /dashboard'); } else { SessionManager::flash('error', 'Invalid credentials'); }
6.2. Namespaced E-Commerce
UserSession::set('logged_in', true); CartSession::set('total', 99.99); echo CartSession::all(); // ['total' => 99.99] SessionManager::namespace('user'); // Switch back
7. Security Considerations
-
Defaults: HTTP-only, SameSite=Lax, strict mode enabled.
-
Regeneration: Auto every 10min; manual via
regenerate(). -
Timeouts: 30min inactivity → auto-destroy.
-
Persistent Sessions: Use secure cookies; validate user on resume (e.g., DB token).
-
Large Data: Avoid storing files/objects; use DB/Redis for >1MB.
-
File Handler: Auto-clears oversized/corrupt sessions; consider Redis for scale.