Simple, pure PHP session management
composer require pipe/sessionRequires PHP 8.2 or newer. No runtime dependencies.
use Pipe\Session;
$session = new Session(); // does not start anything
$session->set('user_id', 123); // first write starts the session
$userId = $session->get('user_id');
$session->set('flash', 'Saved!'); // flash message ...
$message = $session->pluck('flash'); // ... read once, then gone
$session->regenerate(); // after login: new session ID, same data
$session->destroy(); // logout: data deleted, cookie expired- Creating a
Sessiondoesn't start PHP's session. - Writes (
set,regenerate,id(true)) start the session. - Reads (
get,has,all,pluck,delete,clear,destroy) start it only if the client sent a session cookie. Without one they return the default and do nothing, so visitors who never get a session never receive a cookie.
| Setting | Default |
|---|---|
| Cookie name | pipesess |
HttpOnly |
on |
SameSite |
Lax |
Secure |
automatic: on when the request came over HTTPS (HTTPS, REQUEST_SCHEME or port 443). Proxy headers aren't trusted, so set it explicitly behind a TLS-terminating proxy. |
| Lifetime | 0, which lasts until the browser closes |
session.use_strict_mode |
on, so session IDs the server never issued are rejected |
session.use_only_cookies / use_trans_sid |
on / off, so IDs never appear in URLs |
Change these before the session starts:
$session = new Session('myapp', ['samesite' => 'Strict', 'secure' => true, 'lifetime' => 3600]);
// or fluently: (new Session())->name('myapp')->lifetime(3600)->cookie(['domain' => '.example.com'])| Method | Description |
|---|---|
new Session(string $name = 'pipesess', array $cookie = []) |
Configure without starting. |
name(string $name), lifetime(int $seconds), cookie(array $params) |
Settings. The cookie keys are lifetime, path, domain, secure (bool, or null for automatic), httponly and samesite (Lax, Strict or None; None requires secure). Changing settings after the session has started throws LogicException. |
start(): self |
Starts or resumes the session explicitly. Throws RuntimeException when sessions are disabled or output has already started. |
started(): bool |
Whether the session is active. |
get(string $key, mixed $default = null), has(string $key), all() |
Read. |
set(string $key, mixed $value), delete(string $key), clear() |
Write. |
pluck(string $key, mixed $default = null) |
Read a value and remove it, for flash messages. |
regenerate(): self |
A new session ID; the old session data is deleted. Call it after authentication. |
id(bool $new = false): string |
The current ID, or "" when there is no session. id(true) regenerates first. |
destroy(): self |
Deletes the data and sends an expired cookie. |
composer install
composer test- Small is Beautiful.
- Do one thing,
- Do one thing well.
- Get the PoC out ASAP.
- Consider your code dead two weeks after inception.
- n'joy!
sounds familiar? It should!