Skip to content

Recipes

Muhammet Şafak edited this page May 29, 2026 · 1 revision

Recipes

Practical, copy-pasteable patterns built on the public API. Each recipe is self-contained and links back to the reference material for the methods it uses.

Recipe Solves
Authentication & Fixation Login/logout done safely, with id regeneration.
Flash Messages One-shot notices that survive exactly one redirect.
Database-Backed Sessions Storing sessions in MySQL/PostgreSQL/SQLite via PDO.

If you build something reusable on top of the package, please open an issue with a sketch — recipe contributions are welcome.

Choosing where to start a session

A common bootstrap that picks an adapter from configuration:

use InitPHP\Sessions\Session;
use InitPHP\Sessions\Adapters\{FileAdapter, RedisAdapter, PDOAdapter};

$adapter = match (getenv('SESSION_DRIVER') ?: 'file') {
    'redis' => new RedisAdapter(['host' => '127.0.0.1', 'port' => 6379, 'ttl' => 86400]),
    'pdo'   => new PDOAdapter(['dsn' => getenv('DB_DSN'), 'username' => getenv('DB_USER'), 'password' => getenv('DB_PASS'), 'table' => 'sessions']),
    default => new FileAdapter(['path' => __DIR__ . '/storage/sessions']),
};

Session::createImmutable($adapter)->start();

Always start before you read

A tiny guard you can call from a front controller:

if (!Session::isStarted()) {
    Session::createImmutable($adapter)->start([
        'cookie_httponly' => true,
        'cookie_samesite' => 'Lax',
        'cookie_secure'   => !empty($_SERVER['HTTPS']),
    ]);
}

Clone this wiki locally