Search by

seba1rx / sessionadmin

seba1rx

PHP session management with security hardening, hijacking detection, and URL authorization for MPA and SPA applications

Package info

github.com/seba1rx/SessionAdmin

pkg:composer/seba1rx/sessionadmin

Statistics

Installs: 100

Dependents: 1

Suggesters: 1

Stars: 3

Open Issues: 0

v3.0.3 2026-12-01 02:51 UTC

This package is auto-updated.

Last update: 2026-12-01 03:08:18 UTC


README

PHP session management library with security hardening and URL authorization.

composer require seba1rx/sessionadmin

Features

Session security

  • Named sessions with configurable cookie parameters; one HttpOnly (and Secure on HTTPS) session cookie per request
  • Hijacking detection: IP prefix + User-Agent fingerprint verified on every request
  • Proxy-aware IP detection (reads X-Forwarded-For and equivalent headers)
  • Session destruction when a request arrives after the configured lifetime
  • Session ID replaced on login (old session deleted, never authenticated) to prevent fixation; logout, expiry and hijacking detection always end with a new id
  • Optional random id rotation ($rotationChance, off by default) with a grace period for parallel requests

URL authorization (MPA)

  • Define an $allowedUrls list; guests are redirected to index.php on any unlisted page
  • Expandable per user role or profile
  • Disable entirely for SPA apps ($appIsSpa = true, the default)

Quick start

SessionAdmin is abstract with no abstract methods. Extend it and define a constructor:

// App/MySession.php
namespace App;

use Seba1rx\SessionAdmin\SessionAdmin;

class MySession extends SessionAdmin
{
    public function __construct()
    {
        $this->sessionName     = 'my_app';
        $this->sessionLifetime = 3600;          // seconds
        $this->keys            = ['theme' => 'light']; // pre-seeded session keys
    }
}

Then on every entry point, before any output:

require 'vendor/autoload.php';

$session = new App\MySession();
$session->useAuthorization  = false; // true for MPA URL enforcement
$session->activateSession();         // replaces session_start()

// On login:
$session->createUserSession($userId);

// On logout:
$session->terminate();

// Auth check:
if (!empty($_SESSION['sessionadmin']['isUser'])) {
    // authenticated
}

Public API

Method Description
activateSession() Starts or resumes the session; runs all security checks
createUserSession(mixed $id) Marks session as authenticated, regenerates session ID
terminate() Destroys session, reinitialises as guest, redirects to index.php (MPA)
setSessionHandler(\SessionHandlerInterface $handler) Plug in a custom storage backend; call before activateSession()
setTabHandler(TabHandlerInterface $handler) Inject a tab handler (e.g. seba1rx/tabmanager); call before activateSession()

The full class is documented via docblocks — your IDE will surface every property and its purpose.

Session cookie

Each request ends with exactly one session Set-Cookie, always HttpOnly (and Secure when the request is HTTPS), using the attributes of session_get_cookie_params() (path, domain, secure, samesite). PHP sends it when the id is new or regenerated (first visit, login, random regeneration); otherwise the library sends a single refresh cookie with identical attributes so the expiration slides by $sessionLifetime.

Recommended php.ini hardening:

session.use_strict_mode = 1   ; reject ids the server did not issue (session fixation)
session.cookie_samesite = Lax ; inherited by the session cookie

Versions up to 3.0.0 re-sent the cookie without HttpOnly/Secure/domain. Upgrade to 3.0.1 — see CHANGELOG.md.

Session id lifecycle

Event What happens to the id
createUserSession() The id is replaced before the session is marked authenticated; the old id keeps only a tombstone. The pre-login id is never authenticated. Guest data of the same request moves to the new id. If the id cannot be replaced (e.g. output already sent) a SessionAdminException is thrown and nothing is authenticated.
terminate() The current id is buried (a tombstone is written and read back) and the request ends as a guest with a new id — also with session.use_strict_mode=0. The id the browser sent is not resumed.
Expiry, hijacking detected The session is destroyed (deleted, no tombstone) and the request ends as a guest with a new id.
Random rotation Off by default. Set $rotationChance (0–100, % of authenticated requests) in your constructor to enable it.

Tombstones: replaced and buried ids

When login replaces an id, or logout buries it, the old id is not deleted: it keeps a tombstone, a record with only an expiry mark (replacedUntil) — no user, no guest data, no pointer to the new id. Deleting would be unsafe: with PHP's file handler a request already queued on the session lock reads the removed record when it wakes up and stays authenticated.

A request that presents a tombstoned id (a parallel request that carried the old cookie) is handled as a guest without a session cookie: sending one would overwrite the good cookie the browser just received. After $replacedIdTtl seconds (default 60) the tombstone is destroyed and the visitor gets a fresh id with a cookie.

Extension points for code that opens sessions by itself (for example a framework that releases the session early and reopens it with session_start()): sessionIsReplaced() (call it right after session_start()), detachSession() (turns the session into a guest session without a cookie), queuedSessionCookies() and removeQueuedSessionCookie(). They are protected: do not declare members with those names in your subclass unless you mean to override them. tombstone(), buryAndRestart() and $replacedIdTtl are protected too.

Limits (not covered):

  • Handlers without locking. A request that read the session before a login or logout and ends after it writes its old data back over the tombstone (after a logout, an authenticated session comes back). The same happened before with deletion. Use a handler that locks the session (PHP's files handler, or one that implements locking).
  • Lifetime. The tombstone lasts min($replacedIdTtl, session.gc_maxlifetime); a store that drops it earlier makes that id behave as an unknown one (a guest with a cookie, the pre-3.0.3 behaviour). A request carrying the old id that reaches the server more than $replacedIdTtl seconds after the login gets a new guest cookie.
  • Order on the network. If the response with the old id leaves the server before the login but the browser processes it after the response of the login, the old cookie wins. The server cannot prevent it.
  • Applications that release the session before the end of the request (session_write_close() early) need their own handling too: 3.0.3 closes the races that happen on the server's session lock, not those between a cookie queued early and a login that runs later.
  • Two simultaneous logins with the same guest id leave two valid ids; the first request of a visitor without a cookie that is in flight during a login cannot be correlated with it.

Random rotation and parallel requests: when an id is rotated, requests that were already in flight with the old cookie (typical in SPAs) would end as guests and could overwrite the good cookie. $rotationGraceSeconds (default 30) keeps the old id as a data-less pointer to the new session for that long: such requests continue as the user, the holder of the old id is not given the new id, and terminate() kills the pointer's target. 0 deletes the old session at once (simplest, but parallel requests can log the user out). Only enable rotation if you accept a short window in which a stolen old id still works.

class MySession extends SessionAdmin
{
    public function __construct()
    {
        $this->rotationChance       = 3;  // ~3% of authenticated requests rotate the id
        $this->rotationGraceSeconds = 30; // in-flight requests with the old cookie keep working
    }
}

Upgrading from ≤ 3.0.1 (security fix in 3.0.2): updating the code does not invalidate sessions that were already authenticated and may have been duplicated under older ids. Flush your session store on deploy so every user logs in again. See CHANGELOG.md.

Session data written to $_SESSION['sessionadmin']

Key Present Description
appType Always 'SPA' or 'MPA' — reflects the $appIsSpa flag
isUser Always true when authenticated, false for guests
id_user After login Value passed to createUserSession()
msg Always Human-readable state label
uniqueId Always 12-char hex token, stable for the session lifetime
ipPrefix Always First N octets of the client IP (hijacking detection)
userAgent Always User-Agent string (hijacking detection)
time_atRequest Always Unix timestamp of the last request
time_sinceLastRequest Always Seconds elapsed since the previous request
allowedUrl MPA only Copy of $allowedUrls used for URL authorization
urlIsAllowedToLoad MPA only true when the current URL is in the allow-list

allowedUrl and urlIsAllowedToLoad are omitted entirely in SPA mode — they only make sense when URL authorization is active.

Custom session storage

By default the package uses PHP's native file-based session storage. Pass any SessionHandlerInterface implementation to setSessionHandler() before calling activateSession() to swap the backend:

$session = new App\MySession();
$session->setSessionHandler(new RedisSessionHandler($redis));
$session->activateSession();

Any PSR-compatible or custom handler works — Redis, database, encrypted file store, etc. The handler must be set before activateSession() because PHP applies the handler prior to calling session_start().

Tab isolation (optional)

Per-browser-tab session isolation is provided by the companion package seba1rx/tabmanager, which implements TabHandlerInterface.

composer require seba1rx/tabmanager

Inject it before calling activateSession() using SessionAdminBridge — the integration class shipped with tabmanager:

use Seba1rx\TabManager\Bridge\SessionAdminBridge;

$session = new App\MySession();
$session->setTabHandler(new SessionAdminBridge());
$session->autoCleanupTabs = 30; // optional: remove tabs inactive for > 30 s
$session->activateSession();

// After the JS client has registered the tab:
$session->tabHandler->set('cart', ['apple' => 3]);
$cart  = $session->tabHandler->get('cart');
$ready = $session->tabHandler->isTabIndexed(); // false until JS registers the tab

SessionAdminBridge extends TabManager but does not call session_start() in its constructor — activateSession() owns the session lifecycle and configures the session name and cookie parameters before the session starts. Both packages write to distinct keys in $_SESSION (sessionadmin vs tabmanager) and do not interfere with each other.

Tab session loss (autoCleanupTabs + tabmanager:session-lost)

When $autoCleanupTabs is set, SessionAdmin prunes inactive tabs on every activateSession() call. If the browser suspends a tab (Chrome Memory Saver, OS memory pressure), the JS heartbeat pauses — and the tab may be pruned while invisible. When the user returns, tabmanager's JS client checks /tabmanager/tab-status. If the tab is no longer indexed, it fires a tabmanager:session-lost event on document and stops the heartbeat. Listen for this event to show a warning or prompt the user to reload:

document.addEventListener('tabmanager:session-lost', () => {
    // Tab data was pruned by autoCleanupTabs while the tab was suspended.
    // Show a warning and let the user decide whether to reload.
    showSessionLostBanner();
});

The event carries event.detail.tabId with the UUID of the lost tab.

Contracts (interfaces)

The package ships two interfaces under Seba1rx\SessionAdmin\Contracts:

Interface Role Key methods
SessionInterface Implemented by SessionAdmin activateSession(), createUserSession(), terminate()
TabHandlerInterface Implemented by seba1rx/tabmanager set(), get(), isTabIndexed(), cleanupInactiveTabs(), …

TabHandlerInterface defines the full tab lifecycle contract. Any class implementing it can be injected via setTabHandler() — SessionAdmin never depends on the concrete TabManager class.

Example — mock session in tests:

$mockSession = $this->createMock(SessionInterface::class);
$mockSession->expects($this->once())->method('activateSession');

Example — mock tab handler in tests:

$mockTabs = $this->createMock(TabHandlerInterface::class);
$mockTabs->method('get')->with('cart')->willReturn(['apple' => 3]);
$session->setTabHandler($mockTabs);

Demos

Demo Description
demo/basic/ Minimal login/logout — the simplest possible implementation
demo/mpa/ Multi-page app with URL authorization and $allowedUrls
demo/spa/ Single-page app, SPA mode, AJAX login
demo/tabmanager/ SessionAdmin + TabManager integration — shared session, per-tab data isolation

Each demo is self-contained with its own composer.json.

Running a demo locally

  1. Install dependencies for the chosen demo:
cd demo/basic
composer install
  1. Start PHP's built-in web server from the demo directory:
php -S localhost:8000
  1. Open your browser and navigate to:
http://localhost:8000

The built-in server serves index.php by default. Change the port if 8000 is already in use (php -S localhost:8080).