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

0.0.99 2025-11-11 04:24 UTC

This package is auto-updated.

Last update: 2025-11-24 18:51:56 UTC


README

Table of Contents

icon 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

init(array $options = []): void

Start session with config. Idempotent.

5.2. Core Storage

Method

Description

set(string $key, mixed $value): void

Store value; updates activity.

get(string $key, mixed $default = null): mixed

Retrieve value.

has(string $key): bool

Key exists?

delete(string $key): void

Remove key.

all(): array

All namespace data.

clear(): void

Empty current namespace.

5.3. Namespacing

Method

Description

namespace(string $namespace): void

Switch namespace.

currentNamespace(): string

Active namespace.

5.4. Flash Messages

Method

Description

flash(string $key, mixed $value): void

Set for next request.

getFlash(string $key, mixed $default = null): mixed

Get and erase.

hasFlash(string $key): bool

Exists? (non-destructive).

5.5. Security & Lifecycle

Method

Description

regenerate(bool $deleteOld = true): void

New ID; updates activity.

setRegenerateInterval(int $seconds): void

Interval (min 60s).

setTimeout(int $seconds): void

Inactivity timeout (min 1s).

destroy(): void

Full logout (clears data/cookie).

id(): string

Raw session ID.

5.6. Remember Me

Method

Description

enableRememberMe(int $lifetime = 2592000): void

Enable persistent (regenerates ID).

disableRememberMe(): void

Disable (session-only).

isRememberMe(): bool

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.