PHPackages                             codemonster-ru/session - 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. [Framework](/categories/framework)
4. /
5. codemonster-ru/session

ActiveLibrary[Framework](/categories/framework)

codemonster-ru/session
======================

Lightweight session management library for PHP with pluggable handlers

v2.0.0(4mo ago)01372MITPHPPHP &gt;=8.2CI passing

Since Oct 24Pushed 4mo agoCompare

[ Source](https://github.com/codemonster-ru/session)[ Packagist](https://packagist.org/packages/codemonster-ru/session)[ Docs](https://github.com/codemonster-ru/session)[ RSS](/packages/codemonster-ru-session/feed)WikiDiscussions main Synced 1mo ago

READMEChangelog (3)Dependencies (4)Versions (4)Used By (2)

codemonster-ru/session
======================

[](#codemonster-rusession)

[![Latest Version on Packagist](https://camo.githubusercontent.com/399f3429762fcae6550a495c44b3c65077c9910c6caa7394ec95b32e68407b2b/68747470733a2f2f696d672e736869656c64732e696f2f7061636b61676973742f762f636f64656d6f6e737465722d72752f73657373696f6e2e7376673f7374796c653d666c61742d737175617265)](https://packagist.org/packages/codemonster-ru/session)[![Total Downloads](https://camo.githubusercontent.com/af8a44a8f31ca906d1523a8217d50bba51a058cead77fbccf92c35a790d79899/68747470733a2f2f696d672e736869656c64732e696f2f7061636b61676973742f64742f636f64656d6f6e737465722d72752f73657373696f6e2e7376673f7374796c653d666c61742d737175617265)](https://packagist.org/packages/codemonster-ru/session)[![License](https://camo.githubusercontent.com/304c8fc826aea975fa50be5b1dee93819fb76ba4042b5e55975564ac4f80b384/68747470733a2f2f696d672e736869656c64732e696f2f7061636b61676973742f6c2f636f64656d6f6e737465722d72752f73657373696f6e2e7376673f7374796c653d666c61742d737175617265)](https://packagist.org/packages/codemonster-ru/session)[![Tests](https://github.com/codemonster-ru/session/actions/workflows/tests.yml/badge.svg)](https://github.com/codemonster-ru/session/actions/workflows/tests.yml)[![Coverage](https://camo.githubusercontent.com/02ae7bfec6642b591ee928e10414b9fd083d168ae70895c052c74012783d281f/68747470733a2f2f636f6465636f762e696f2f67682f636f64656d6f6e737465722d72752f73657373696f6e2f6272616e63682f6d61696e2f67726170682f62616467652e737667)](https://codecov.io/gh/codemonster-ru/session)

**Lightweight session management library for PHP** - object-oriented.

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

[](#installation)

```
composer require codemonster-ru/session
```

Usage
-----

[](#usage)

### Basic example

[](#basic-example)

```
use Codemonster\Session\Session;

// Start session (default: file storage)
Session::start();

// Store values
Session::put('user', 'Vasya');
Session::put('role', 'admin');

// Retrieve values
echo Session::get('user'); // Vasya

// Remove values
Session::forget('role');

// Get all session data
print_r(Session::all());

// Destroy current session
Session::destroy();
```

### Regenerating session ID (fixation protection)

[](#regenerating-session-id-fixation-protection)

```
// Rotate ID after login or privilege change
Session::regenerate();
```

### Regenerating on start

[](#regenerating-on-start)

```
// Force new ID at start (keeps data, destroys old session)
Session::start(options: ['regenerate' => true]);
```

### Cookie options

[](#cookie-options)

```
Session::start(options: [
    'cookie' => [
        'secure' => true,
        'samesite' => 'Strict',
        'lifetime' => 3600,
        'path' => '/',
        'domain' => 'example.com'
    ]
]);
```

Notes:

- If `secure` is not provided, it is set automatically when HTTPS is detected.
- If `samesite` is `None`, `secure` is forced to `true`.

### Production cookie example

[](#production-cookie-example)

```
Session::start(options: [
    'cookie' => [
        'secure' => true,
        'httponly' => true,
        'samesite' => 'Strict',
        'lifetime' => 60 * 60 * 24,
        'path' => '/'
    ]
]);
```

### Encryption

[](#encryption)

```
use Codemonster\Session\Session;

$key = random_bytes(32);

Session::start(options: [
    'encryption' => [
        'key' => $key,
        // Optional: allow decrypting existing plaintext sessions
        // Also triggers auto-migration to encrypted payload on first read
        'allow_plaintext' => true,
        // Optional: previous keys for rotation
        'previous_keys' => []
    ]
]);
```

### Encryption key rotation

[](#encryption-key-rotation)

```
$oldKey = random_bytes(32);
$newKey = random_bytes(32);

Session::start(options: [
    'encryption' => [
        'key' => $oldKey,
        'allow_plaintext' => true
    ]
]);

// rotate to a new key, keeping the old key for decryption
Session::rotateEncryptionKey($newKey, [$oldKey]);
```

### Production encryption example

[](#production-encryption-example)

```
// Store keys in env/secret manager; use base64 for readability.
$currentKey = base64_decode(getenv('SESSION_KEY'), true);
$previousKey = base64_decode(getenv('SESSION_KEY_PREV'), true);

Session::start(options: [
    'encryption' => [
        'key' => $currentKey,
        'previous_keys' => array_filter([$previousKey]),
        'allow_plaintext' => false
    ]
]);
```

### Key rotation strategy

[](#key-rotation-strategy)

1. Deploy with `previous_keys` containing the old key and `key` as the new key.
2. Keep `allow_plaintext=false` if you already migrated to encryption.
3. After rotation window, remove the old key from `previous_keys`.

### Using Array handler (for tests or CLI)

[](#using-array-handler-for-tests-or-cli)

```
Session::start('array');
Session::put('debug', true);

echo Session::get('debug'); // true
```

### Handy helpers

[](#handy-helpers)

```
Session::put('count', 1);
Session::increment('count', 2); // 3

Session::put('token', 'abc');
Session::has('token'); // true
Session::pull('token'); // 'abc'
Session::has('token'); // false

Session::put('a', 1);
Session::put('b', 2);
Session::forgetMany(['a', 'b']);

// Flash data lasts for the next start and is then removed
Session::flash('notice', 'Saved');
```

### TTL for keys

[](#ttl-for-keys)

```
Session::putWithTtl('token', 'abc', 60); // expires in 60 seconds
Session::sweepExpired(); // optional manual cleanup
Session::ttl('token'); // remaining seconds
Session::expiresAt('token'); // unix timestamp
Session::touch('token', 120); // extend TTL
```

### Namespaced sessions

[](#namespaced-sessions)

```
$admin = Session::for('admin');
$user = Session::for('user');

$admin->put('token', 'admin123');
$user->put('token', 'user456');
```

### Namespace helpers

[](#namespace-helpers)

```
$admin = Session::for('admin');
$admin->keys(); // ['token', ...]
$admin->forgetNamespace();
Session::count(); // count of user keys
Session::touchAll(120); // extend TTL for all keys
Session::touchAll(120, 'admin.'); // extend only for namespace

Session::keys(); // ['admin.token', 'user.token', ...]
Session::forgetNamespace('user');
```

### Custom namespace delimiter

[](#custom-namespace-delimiter)

```
$scope = Session::for('admin', ':');
$scope->put('token', 'x'); // stored as admin:token
```

### Debug helpers

[](#debug-helpers)

```
Session::dump(); // array of user-visible keys/values
Session::dump(['token']); // redact selected keys
Session::dump([], ['user*']); // redact by pattern
Session::size(); // payload size in bytes
```

### Key helpers

[](#key-helpers)

```
Session::keys(); // all keys
Session::keysMatch('user*'); // wildcard match
```

### Session manager (non-static)

[](#session-manager-non-static)

```
$manager = Session::manager();
$manager->put('token', 'abc');

$scoped = $manager->for('admin');
$scoped->put('token', 'admin123');
```

### Using custom handler

[](#using-custom-handler)

```
use Codemonster\Session\Session;
use App\Session\RedisSessionHandler;

$redis = new Redis();
$redis->connect('127.0.0.1', 6379);

$handler = new RedisSessionHandler($redis);

Session::start(customHandler: $handler);
Session::put('user_id', 42);
```

### Using Redis handler

[](#using-redis-handler)

```
use Codemonster\Session\Handlers\RedisSessionHandler;
use Codemonster\Session\Session;

$redis = new Redis();
$redis->connect('127.0.0.1', 6379);

$handler = new RedisSessionHandler($redis, prefix: 'sess_', ttl: 3600, retries: 2, retryDelayMs: 100);

Session::start(customHandler: $handler);
```

### Using Redis Cluster handler

[](#using-redis-cluster-handler)

```
use Codemonster\Session\Handlers\RedisClusterSessionHandler;
use Codemonster\Session\Session;

$cluster = new RedisCluster(null, ['127.0.0.1:7000', '127.0.0.1:7001']);

$handler = new RedisClusterSessionHandler($cluster, prefix: 'sess_', ttl: 3600, retries: 2, retryDelayMs: 100);

Session::start(customHandler: $handler);
```

### Using Redis Sentinel handler

[](#using-redis-sentinel-handler)

```
use Codemonster\Session\Handlers\RedisSentinelSessionHandler;
use Codemonster\Session\Session;

$sentinel = new RedisSentinel('127.0.0.1', 26379);

$handler = new RedisSentinelSessionHandler(
    $sentinel,
    service: 'mymaster',
    prefix: 'sess_',
    ttl: 3600,
    retries: 2,
    retryDelayMs: 100
);

Session::start(customHandler: $handler);
```

### Using Predis handler

[](#using-predis-handler)

```
use Codemonster\Session\Handlers\PredisSessionHandler;
use Codemonster\Session\Session;
use Predis\Client;

$client = new Client('tcp://127.0.0.1:6379');

$handler = new PredisSessionHandler($client, prefix: 'sess_', ttl: 3600, retries: 2, retryDelayMs: 100);

Session::start(customHandler: $handler);
```

### Using PSR-16 cache handler

[](#using-psr-16-cache-handler)

```
use Codemonster\Session\Handlers\CacheSessionHandler;
use Codemonster\Session\Session;
use Psr\SimpleCache\CacheInterface;

/** @var CacheInterface $cache */
$handler = new CacheSessionHandler($cache, prefix: 'sess_', ttl: 3600, retries: 2, retryDelayMs: 100);

Session::start(customHandler: $handler);
```

Testing
-------

[](#testing)

You can run tests with the command:

```
composer test
```

Static analysis:

```
composer analyse
composer psalm
```

Redis integration tests (optional):

```
REDIS_TESTS=1 composer test
```

Redis Sentinel/Cluster integration tests (optional):

```
REDIS_SENTINEL_TESTS=1 composer test
REDIS_CLUSTER_TESTS=1 composer test
```

Stress test (optional):

```
composer stress
composer stress -- 20000 array
composer stress -- 20000 file
REDIS_HOST=127.0.0.1 REDIS_PORT=6379 composer stress -- 20000 redis

# With thresholds: iterations, driver, min_ops, max_seconds
composer stress -- 20000 array 3400 6
composer stress -- 10000 file 1700 6
composer stress -- 20000 redis 400 6
```

Note: thresholds depend on runner performance; recalibrate if CI hardware changes.

Security
--------

[](#security)

Security reports: email  with a clear description and steps to reproduce.

Security checklist:

- Use HTTPS and `secure` cookies in production.
- Set `SameSite` to `Strict` or `Lax` based on your flow.
- Use `httponly` to reduce XSS access to cookies.
- Rotate session IDs after login or privilege changes.
- Consider payload encryption (`encryption.key`) for sensitive data.
- Keep session storage private and with proper file permissions.

Author
------

[](#author)

[**Kirill Kolesnikov**](https://github.com/KolesnikovKirill)

License
-------

[](#license)

[MIT](https://github.com/codemonster-ru/session/blob/main/LICENSE)

###  Health Score

38

—

LowBetter than 85% of packages

Maintenance74

Regular maintenance activity

Popularity10

Limited adoption so far

Community10

Small or concentrated contributor base

Maturity50

Maturing project, gaining track record

 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 ~33 days

Total

3

Last Release

140d ago

Major Versions

v1.1.0 → v2.0.02025-12-29

### Community

Maintainers

![](https://www.gravatar.com/avatar/a22c460130c82eca5da633a388faa81adf7e63558a2ae1e34441e6624ec2ad15?d=identicon)[KolesnikovKirill](/maintainers/KolesnikovKirill)

---

Top Contributors

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

---

Tags

codemonsterframeworkhandlerphpsessionphpframeworkhandlersessioncodemonster

###  Code Quality

TestsPHPUnit

Static AnalysisPHPStan, Psalm

Type Coverage Yes

### Embed Badge

![Health badge](/badges/codemonster-ru-session/health.svg)

```
[![Health](https://phpackages.com/badges/codemonster-ru-session/health.svg)](https://phpackages.com/packages/codemonster-ru-session)
```

###  Alternatives

[phalcon/phalcon

Phalcon Framework

2421.5k1](/packages/phalcon-phalcon)[digitalstars/simplevk

Powerful PHP library/framework for VK API bots, supporting LongPoll &amp; Callback &amp; OAuth

883.9k3](/packages/digitalstars-simplevk)[scrawler/router

An Fully Automatic RESTful PHP Router.

552.2k3](/packages/scrawler-router)

PHPackages © 2026

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