PHPackages                             initphp/sessions - PHPackages - PHPackages  [Skip to content](#main-content)[PHPackages](/)[Directory](/)[Categories](/categories)[Trending](/trending)[Leaderboard](/leaderboard)[Changelog](/changelog)[Analyze](/analyze)[Collections](/collections)[Log in](/login)[Sign up](/register)

1. [Directory](/)
2. /
3. [Database &amp; ORM](/categories/database)
4. /
5. initphp/sessions

ActiveLibrary[Database &amp; ORM](/categories/database)

initphp/sessions
================

Framework-agnostic PHP session manager with pluggable save handlers (File, Cookie, PDO, Redis, Memcache/Memcached, MongoDB).

4.0.0(1mo ago)0991MITPHPPHP ^8.1CI passing

Since Jul 25Pushed 3w ago1 watchersCompare

[ Source](https://github.com/InitPHP/Sessions)[ Packagist](https://packagist.org/packages/initphp/sessions)[ RSS](/packages/initphp-sessions/feed)WikiDiscussions main Synced 2d ago

READMEChangelog (5)Dependencies (4)Versions (6)Used By (1)

InitPHP Sessions
================

[](#initphp-sessions)

Framework-agnostic PHP session manager with a small, fluent API and pluggable save handlers. Bring your own backend — files, an encrypted cookie, a SQL database (PDO), Redis, Memcache/Memcached, or MongoDB — behind one consistent interface.

[![CI](https://github.com/InitPHP/Sessions/actions/workflows/ci.yml/badge.svg)](https://github.com/InitPHP/Sessions/actions/workflows/ci.yml)[![License: MIT](https://camo.githubusercontent.com/784362b26e4b3546254f1893e778ba64616e362bd6ac791991d2c9e880a3a64e/68747470733a2f2f696d672e736869656c64732e696f2f62616467652f4c6963656e73652d4d49542d677265656e2e737667)](./LICENSE)

Requirements
------------

[](#requirements)

- PHP 8.1 or later
- Individual adapters may require additional extensions or libraries (see each adapter below).

Installation
------------

[](#installation)

```
composer require initphp/sessions
```

Quick Start
-----------

[](#quick-start)

Bootstrap the facade once with `createImmutable()`, start the session, then read and write values. With no adapter, PHP's default save handler is used.

```
require_once 'vendor/autoload.php';

use InitPHP\Sessions\Session;

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

Session::set('username', 'admin')
    ->set('mail', 'admin@example.com');

echo Session::get('username', 'Undefined');
```

Every method is available both statically (`Session::set(...)`) and on the instance returned by `createImmutable()` — the two styles are interchangeable. You can keep using `$_SESSION` directly if you prefer; the facade is a convenience layer, not a replacement.

```
$_SESSION['username'] = 'admin';
echo $_SESSION['username'] ?? 'Undefined';
```

The `Session` API
-----------------

[](#the-session-api)

### Reading &amp; writing values

[](#reading--writing-values)

MethodReturnsDescription`has(string $key)``bool`Whether the key exists.`set(string $key, mixed $value)``GetterSetter`Store a value (chainable).`get(string $key, mixed $default = null)``mixed`Read a value, or `$default`.`push(string $key, mixed $value)``mixed`Store and return the value itself.`pull(string $key, mixed $default = null)``mixed`Read, then remove the key.`remove(string ...$keys)` / `delete(...)``GetterSetter`Remove one or more keys.`all()``array`The whole session payload.`setAssoc(array $assoc, bool $reset = false)``GetterSetter`Merge (or replace) many string-keyed values.### Managing the session lifecycle

[](#managing-the-session-lifecycle)

MethodReturnsDescription`start(array $options = [])``bool`Register the adapter (if any) and start the session.`isStarted()``bool`Whether a session is currently active.`getName()` / `setName(string $name)``string` / `Manager`Read / set the session name (before `start()`).`getID()` / `setID(string $id)``string` / `bool`Read / set the session id (before `start()`).`regenerateId(bool $deleteOld = false)``bool`Issue a fresh session id.`flush()` / `unset()``bool`Clear all session variables (requires an active session).`destroy()``bool`Destroy the session entirely.Adapters
--------

[](#adapters)

All adapters implement `InitPHP\Sessions\Interfaces\AdapterInterface`, which extends PHP's native `SessionHandlerInterface`. Pass an adapter to `createImmutable()` and it becomes the session's save handler.

### File

[](#file)

Stores sessions as files in a directory you choose, without touching the global `session.save_path`.

```
use InitPHP\Sessions\Session;
use InitPHP\Sessions\Adapters\FileAdapter;

$adapter = new FileAdapter([
    'path'   => '/var/www/storage/sessions', // required, writable directory
    'prefix' => 'sess_',                      // optional, default "sess_"
]);

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

### Redis

[](#redis)

Requires `ext-redis`. Provide connection details inline, or reuse an existing `\Redis` instance via the `redis` option.

```
use InitPHP\Sessions\Session;
use InitPHP\Sessions\Adapters\RedisAdapter;

$adapter = new RedisAdapter([
    'host'     => '127.0.0.1', // string
    'port'     => 6379,        // int
    'timeout'  => 0,           // float, connect timeout (seconds)
    'password' => null,        // null or string (AUTH)
    'database' => 0,           // int (SELECT)
    'ttl'      => 86400,       // int, key expiry (seconds)
    'prefix'   => 'sess_',     // optional key prefix
]);

// Or reuse an existing client:
// $adapter = new RedisAdapter(['redis' => $existingRedis, 'ttl' => 86400]);

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

### PDO

[](#pdo)

Requires `ext-pdo` and a driver (MySQL, PostgreSQL, SQLite, ...). Pass an existing `PDO` instance, or a `dsn` to let the adapter connect.

```
use InitPHP\Sessions\Session;
use InitPHP\Sessions\Adapters\PDOAdapter;

$pdo = new PDO('mysql:host=localhost;dbname=test', 'root', '');

$adapter = new PDOAdapter([
    'pdo'           => $pdo,          // or 'dsn' => '...', 'username' => '...', 'password' => '...'
    'table'         => 'sessions',    // required
    'withIPAddress' => false,         // optional: also match the client IP on read/destroy
]);

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

Example table (MySQL):

```
CREATE TABLE `sessions` (
    `id`              VARCHAR(255) NOT NULL,
    `sess_timestamp`  DATETIME NULL DEFAULT NULL,
    `sess_ip_address` VARCHAR(48) DEFAULT NULL,
    `sess_data`       TEXT NOT NULL,
    PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;
```

### Cookie

[](#cookie)

Stores the whole session payload in an encrypted, base64-encoded cookie — no server-side storage. Requires `initphp/encryption`:

```
composer require initphp/encryption
```

```
use InitPHP\Sessions\Session;
use InitPHP\Sessions\Adapters\CookieAdapter;

$adapter = new CookieAdapter([
    'name'     => 'app_session',     // required
    'key'      => 'your-secret-key', // required, encryption key
    'ttl'      => 86400,             // optional, default 86400
    'secure'   => true,              // optional, HTTPS only (default false)
    'httponly' => true,              // optional, hide from JS (default true)
    'samesite' => 'Lax',             // optional, Lax|Strict|None (default Lax)
]);

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

### Memcache / Memcached

[](#memcache--memcached)

Requires `ext-memcached` (preferred) or `ext-memcache`. The driver is detected automatically.

```
use InitPHP\Sessions\Session;
use InitPHP\Sessions\Adapters\MemCacheAdapter;

$adapter = new MemCacheAdapter([
    'host'   => '127.0.0.1', // string
    'port'   => 11211,       // int
    'weight' => 1,           // int
    'raw'    => false,       // bool, binary protocol (Memcached only)
    'prefix' => '',          // optional key prefix
    'ttl'    => 86400,       // int, item expiry (seconds)
]);

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

### MongoDB

[](#mongodb)

Requires `ext-mongodb`.

```
use InitPHP\Sessions\Session;
use InitPHP\Sessions\Adapters\MongoDBAdapter;

$adapter = new MongoDBAdapter([
    'dsn'        => 'mongodb://127.0.0.1:27017',  // required
    'collection' => 'app.sessions',               // required, "database.collection"
]);

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

Custom Adapters
---------------

[](#custom-adapters)

Extend `InitPHP\Sessions\AbstractAdapter` and implement `read()`, `write()` and `destroy()`. `open()`, `close()` and `gc()` have sensible defaults you can override:

```
use InitPHP\Sessions\AbstractAdapter;

final class ArrayAdapter extends AbstractAdapter
{
    /** @var array */
    private array $store = [];

    public function read(string $id): string|false
    {
        return $this->store[$id] ?? '';
    }

    public function write(string $id, string $data): bool
    {
        $this->store[$id] = $data;

        return true;
    }

    public function destroy(string $id): bool
    {
        unset($this->store[$id]);

        return true;
    }
}
```

Error Handling
--------------

[](#error-handling)

The package throws a small, predictable set of exceptions, all rooted at `InitPHP\Sessions\Exceptions\SessionException`:

ExceptionWhen`SessionException`Base type; a `session_*()` lifecycle call failed.`SessionAdapterException`An adapter failed to reach its backing store (connection, auth, driver). Extends `SessionException`.`SessionInvalidArgumentException`Missing or invalid adapter options. Extends `\InvalidArgumentException`.`SessionNotSupportedAdapter`A required extension or library is unavailable. Extends `\RuntimeException`.```
use InitPHP\Sessions\Exceptions\SessionException;

try {
    Session::createImmutable($adapter)->start();
} catch (SessionException $e) {
    // Covers both lifecycle and adapter failures.
}
```

Documentation
-------------

[](#documentation)

In-depth, copy-pasteable docs live in [`docs/`](./docs/README.md).

Quality
-------

[](#quality)

```
composer test     # PHPUnit
composer phpstan  # Static analysis (level 8)
composer cs-check # Coding style (PSR-12)
composer qa       # All of the above
```

Migrating from `initphp/redis-session-handler`
----------------------------------------------

[](#migrating-from-initphpredis-session-handler)

The standalone [`initphp/redis-session-handler`](https://github.com/InitPHP/RedisSessionHandler)package is deprecated in favour of this one. The `RedisAdapter` here is a superset: TTL support, typed exceptions and the unified `Session` API.

**Before:**

```
$redis = new \InitPHP\Redis\Redis(['host' => '127.0.0.1', 'port' => 6379]);
$handler = new \InitPHP\RedisSessionHandler\Handler($redis);
session_set_save_handler($handler, true);
session_start();
```

**After:**

```
use InitPHP\Sessions\Session;
use InitPHP\Sessions\Adapters\RedisAdapter;

$adapter = new RedisAdapter([
    'host'     => '127.0.0.1',
    'port'     => 6379,
    'database' => 0,
    'ttl'      => 86400,
    'prefix'   => 'sess_',
]);

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

This adapter talks directly to `ext-redis` (or an existing `\Redis` instance passed via the `redis` option), so the `initphp/redis` wrapper is no longer required. Pass the `prefix` option if you want to keep the previous `sess_`prefix exactly.

Credits
-------

[](#credits)

- [Muhammet ŞAFAK](https://github.com/muhammetsafak) &lt;&gt;

License
-------

[](#license)

Copyright © 2022 [MIT License](./LICENSE)

###  Health Score

46

—

FairBetter than 92% of packages

Maintenance94

Actively maintained with recent releases

Popularity10

Limited adoption so far

Community9

Small or concentrated contributor base

Maturity60

Established project with proven stability

 Bus Factor1

Top contributor holds 100% of commits — single point of failure

How is this calculated?**Maintenance (25%)** — Last commit recency, latest release date, and issue-to-star ratio. Uses a 2-year decay window.

**Popularity (30%)** — Total and monthly downloads, GitHub stars, and forks. Logarithmic scaling prevents top-heavy scores.

**Community (15%)** — Contributors, dependents, forks, watchers, and maintainers. Measures real ecosystem engagement.

**Maturity (30%)** — Project age, version count, PHP version support, and release stability.

###  Release Activity

Cadence

Every ~351 days

Total

5

Last Release

35d ago

Major Versions

1.0 → 2.02022-12-09

2.0.1 → 3.02023-12-16

3.0 → 4.0.02026-05-29

PHP version history (4 changes)1.0PHP &gt;=7.2

2.0PHP &gt;=7.4

3.0PHP &gt;=8.0

4.0.0PHP ^8.1

### Community

Maintainers

![](https://www.gravatar.com/avatar/4b6b34f3ac8938d8ee52ba3bd260680855dc5715c7b2929d9380de30d15a67dd?d=identicon)[muhammetsafak](/maintainers/muhammetsafak)

---

Top Contributors

[![muhammetsafak](https://avatars.githubusercontent.com/u/104234499?v=4)](https://github.com/muhammetsafak "muhammetsafak (9 commits)")

---

Tags

cookieinitphpmemcachedmongodbpdophpphp8redissave-handlersessionsession-handlersession-managementsessionsmysqlsqlitepostgresqlpdoredismemcachedmongodbsessioncookiesessionsmemcachesession handlerinitphpsave handler

###  Code Quality

TestsPHPUnit

Static AnalysisPHPStan

Code StylePHP CS Fixer

Type Coverage Yes

### Embed Badge

![Health badge](/badges/initphp-sessions/health.svg)

```
[![Health](https://phpackages.com/badges/initphp-sessions/health.svg)](https://phpackages.com/packages/initphp-sessions)
```

###  Alternatives

[apix/cache

A thin PSR-6 cache wrapper with a generic interface to various caching backends emphasising cache taggging and indexing to Redis, Memcached, PDO/SQL, APC and other adapters.

117548.2k6](/packages/apix-cache)[doctrine/dbal

Powerful PHP database abstraction layer (DBAL) with many features for database schema introspection and management.

9.7k605.0M6.8k](/packages/doctrine-dbal)[phpfastcache/phpfastcache

PHP Abstract Cache Class - Reduce your database call using cache system. Phpfastcache handles a lot of drivers such as Apc(u), Cassandra, CouchBase, Couchdb, Dynamodb, Firestore, Mongodb, Files, (P)redis, Leveldb, Memcache(d), Ravendb, Ssdb, Sqlite, Wincache, Xcache, Zend Data Cache.

2.5k5.3M141](/packages/phpfastcache-phpfastcache)[matthiasmullie/scrapbook

Scrapbook is a PHP cache library, with adapters for e.g. Memcached, Redis, Couchbase, APCu, SQL and additional capabilities (e.g. transactions, stampede protection) built on top.

3232.8M45](/packages/matthiasmullie-scrapbook)[malkusch/lock

Mutex library for exclusive code execution.

96410.1M29](/packages/malkusch-lock)[nette/database

💾 Nette Database: layer with a familiar PDO-like API but much more powerful. Building queries, advanced joins, drivers for MySQL, PostgreSQL, SQLite, MS SQL Server and Oracle.

5687.0M262](/packages/nette-database)

PHPackages © 2026

[Directory](/)[Categories](/categories)[Trending](/trending)[Changelog](/changelog)[Analyze](/analyze)
