PHPackages                             victory7/ezsession - 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. [Authentication &amp; Authorization](/categories/authentication)
4. /
5. victory7/ezsession

ActiveLibrary[Authentication &amp; Authorization](/categories/authentication)

victory7/ezsession
==================

ezsession is a versatile PHP session handler designed to provide seamless session management by combining the strengths of relational databases (MySQL), key-value stores (Redis), and JWT tokens. It offers developers flexible, secure, and scalable session storage, making it ideal for applications requiring high-performance, distributed, and stateless authentication systems. With ezsession, you can customize your session storage strategy to suit a variety of use cases while ensuring enhanced security and simplified management.

0.1.4(1y ago)210MITPHP

Since Oct 20Pushed 1y ago1 watchersCompare

[ Source](https://github.com/victory7/ezsession)[ Packagist](https://packagist.org/packages/victory7/ezsession)[ RSS](/packages/victory7-ezsession/feed)WikiDiscussions main Synced today

READMEChangelogDependencies (5)Versions (6)Used By (0)

EzSession - Standalone by JWT, Write &amp; Read On-Demand
=========================================================

[](#ezsession---standalone-by-jwt-write--read-on-demand)

`ezsession` is a PHP session management library focused on an on-demand write and read strategy to optimize session data handling. It efficiently manages sessions using in-memory cache (e.g., Redis), permanent storage (e.g., MySQL), and JWT tokens, minimizing unnecessary storage queries and providing easy access to JWT for custom data handling. This approach ensures that session data is only written when required, significantly reducing storage operations and improving overall performance.

Features
--------

[](#features)

- **Write-On-Demand**: Data is only written to storage when necessary, reducing the number of storage operations.
- **Flexible Backend Storage**: Uses Redis, memcached, APCu, ... for caching, SQLight, MySQL, Postgres, MongoDB, ... for persistent storage, and JWT for stateless session management.
- **Easy Integration**: Plug-and-play session management for PHP applications.
- **Scalable &amp; Secure**: Optimizes read and write operations to ensure data persistence and secure session management.

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

[](#requirements)

- PHP 7.4 or higher
- Redis server (for caching backend)
- MySQL server (for persistent storage)

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

[](#installation)

You can install `ezsession` using Composer. Simply run:

```
composer require victory7/ezsession
```

Then, include the autoloader in your script:

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

Configuration
-------------

[](#configuration)

### Redis &amp; MySQL Setup

[](#redis--mysql-setup)

Before using `ezsession`, make sure you have access to a running Redis and MySQL server. Update your database credentials and Redis configuration accordingly.

### Usage

[](#usage)

To use `ezsession` in your PHP application, initialize the session handler and start a session as follows:

```
use Ezsession\Ezsession;

// Initialize Ezsession with your Redis and MySQL configuration
$sessionHandler = new Ezsession(
    [
        'redis' => [
            'host' => '127.0.0.1',
            'port' => 6379,
        ],
        'mysql' => [
            'host' => '127.0.0.1',
            'username' => 'root',
            'password' => '',
            'database' => 'ezsession_db',
        ],
        'jwt_secret' => 'your_secret_key_here',
    ]
);

session_set_save_handler($sessionHandler, true);
session_start();

// Example usage
$_SESSION['user_id'] = 123;
$_SESSION['username'] = 'john_doe';
```

### How It Works

[](#how-it-works)

`ezsession` handles session data efficiently by using a combination of JWT tokens, Redis, and MySQL to reduce unnecessary storage operations:

1. **Session Initialization**: On the first request, `ezsession` generates a session ID using a UUID and issues a JWT token signed with your application secret key. This token is returned as a session cookie (with the name defined in the configuration).
2. **Subsequent Requests**: For the rest of the requests, the session token is retrieved either via the same cookie or from the `Authorization` Bearer header. After validation, `ezsession` checks the `"stored"` flag in the JWT:

    - If the `"stored"` flag is `false`, it means there is no data in the cache or permanent storage, so the JWT value is returned to `$_SESSION` and is accessible via `$_SESSION['jwt']`.
    - If nothing has been written to the session, `ezsession` does not write anything to cache or database and does not perform any queries.
3. **Writing to Session**: When something is written to the session (e.g., `$_SESSION['name'] = 'John';`), `ezsession` stores this data in both Redis and MySQL, updates the `"stored"` flag to `true`, and generates a new JWT token. This updated token is then returned to the client, replacing the previous token automatically.
4. **Data Retrieval**: When the `"stored"` flag is `true`, `ezsession` first checks Redis for the data:

    - If the data is found in Redis, it is returned.
    - If not, `ezsession` queries MySQL, and if the data is found, it caches it in Redis for future requests.
5. **Unset Session Values**: If all session values are unset, the `"stored"` flag is set back to `false`, and requests are handled purely through the JWT without accessing cache or database.

### Working with JWT Data

[](#working-with-jwt-data)

A key feature of `ezsession` is the ability to add, modify, or delete custom data in the JWT token directly:

- Access the JWT data using `$_SESSION['jwt']`. For example, you can add a `user_id` to the JWT like this:

```
$_SESSION['jwt']['user_id'] = 'aaBBcc1212';
```

- Modifying the JWT in this way forces `ezsession` to regenerate the token and send it back through subsequent requests, minimizing session storage queries.

### Example Usage

[](#example-usage)

```
// Adding custom data to JWT
$_SESSION['jwt']['role'] = 'admin';
```

Contributing
------------

[](#contributing)

Contributions are welcome! Feel free to fork this repository, make your changes, and submit a pull request. Let's make session management easier for everyone.

License
-------

[](#license)

`ezsession` is licensed under the MIT License. See [LICENSE](LICENSE) for more details.

Support
-------

[](#support)

If you encounter any issues or have questions, please open an issue on GitHub or contact me at .

Future Improvements
-------------------

[](#future-improvements)

- **Enhanced JWT Features**: Add more advanced JWT functionality, such as expiration handling.
- **Flexible Backends**: Support for additional databases and caching systems.
- **Improved Performance**: Further optimize the read/write strategies.

---

Thank you for using `ezsession`! We hope it makes your session management process more enjoyable.

###  Health Score

22

—

LowBetter than 21% of packages

Maintenance35

Infrequent updates — may be unmaintained

Popularity7

Limited adoption so far

Community7

Small or concentrated contributor base

Maturity33

Early-stage or recently created project

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

Total

5

Last Release

615d ago

### Community

Maintainers

![](https://avatars.githubusercontent.com/u/2534020?v=4)[Ali Pourbazargan](/maintainers/victory7)[@victory7](https://github.com/victory7)

---

Top Contributors

[![victory7](https://avatars.githubusercontent.com/u/2534020?v=4)](https://github.com/victory7 "victory7 (12 commits)")

---

Tags

php-librarysessionsession-handler

###  Code Quality

TestsPHPUnit

Code StylePHP\_CodeSniffer

### Embed Badge

![Health badge](/badges/victory7-ezsession/health.svg)

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

###  Alternatives

[directorytree/ldaprecord-laravel

LDAP Authentication &amp; Management for Laravel.

5752.3M18](/packages/directorytree-ldaprecord-laravel)[microsoft/kiota-authentication-phpleague

Authentication provider for Kiota using the PHP League OAuth 2.0 client to authenticate against the Microsoft Identity platform

154.1M9](/packages/microsoft-kiota-authentication-phpleague)[ellaisys/aws-cognito

Laravel Authentication using AWS Cognito (Web and API)

123256.9k1](/packages/ellaisys-aws-cognito)[firefly-iii/data-importer

Firefly III Data Import Tool.

8035.8k](/packages/firefly-iii-data-importer)[mynaparrot/plugnmeet-sdk

plugNmeet PHP SDK

102.8k](/packages/mynaparrot-plugnmeet-sdk)

PHPackages © 2026

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