PHPackages                             jasny/session-middleware - 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. [HTTP &amp; Networking](/categories/http)
4. /
5. jasny/session-middleware

ActiveLibrary[HTTP &amp; Networking](/categories/http)

jasny/session-middleware
========================

PSR-15 session middleware with support for mock sessions

v1.1.0(6y ago)12.2k↓75%2[1 issues](https://github.com/jasny/session-middleware/issues)MITPHPPHP &gt;=7.4.0

Since Jul 12Pushed 6y agoCompare

[ Source](https://github.com/jasny/session-middleware)[ Packagist](https://packagist.org/packages/jasny/session-middleware)[ RSS](/packages/jasny-session-middleware/feed)WikiDiscussions master Synced 1mo ago

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

Session middleware
==================

[](#session-middleware)

[![Build Status](https://camo.githubusercontent.com/b3684e1ea3146850cd02e1f1a865aa76008b46deb8f898fa9e9ac8e8955ed12f/68747470733a2f2f7472617669732d63692e6f72672f6a61736e792f73657373696f6e2d6d6964646c65776172652e7376673f6272616e63683d6d6173746572)](https://travis-ci.org/jasny/session-middleware)[![Scrutinizer Code Quality](https://camo.githubusercontent.com/c76de9cbb5bf12ca76ead596d7580f9338c321eb95e6cd7762045d937e10f4e0/68747470733a2f2f7363727574696e697a65722d63692e636f6d2f672f6a61736e792f73657373696f6e2d6d6964646c65776172652f6261646765732f7175616c6974792d73636f72652e706e673f623d6d6173746572)](https://scrutinizer-ci.com/g/jasny/session-middleware/?branch=master)[![Code Coverage](https://camo.githubusercontent.com/7b7e42d7ce9d75b38c280b86d4054c913d276e0084b3fbc6f813f7d9617cd758/68747470733a2f2f7363727574696e697a65722d63692e636f6d2f672f6a61736e792f73657373696f6e2d6d6964646c65776172652f6261646765732f636f7665726167652e706e673f623d6d6173746572)](https://scrutinizer-ci.com/g/jasny/session-middleware/?branch=master)[![Packagist Stable Version](https://camo.githubusercontent.com/17fe9505e3a92e6fd89b8c3cec20bb16423a2ee050277faa971aebe3f5e1212a/68747470733a2f2f696d672e736869656c64732e696f2f7061636b61676973742f762f6a61736e792f73657373696f6e2d6d6964646c65776172652e737667)](https://packagist.org/packages/jasny/session-middleware)[![Packagist License](https://camo.githubusercontent.com/ab8d6a8e07c66c560ec3d6c3db6924a559ec6330efb7244633e83d1fcb1f7746/68747470733a2f2f696d672e736869656c64732e696f2f7061636b61676973742f6c2f6a61736e792f73657373696f6e2d6d6964646c65776172652e737667)](https://packagist.org/packages/jasny/session-middleware)

Using superglobals like `$_SESSION` object makes it difficult to test an application as global variables can have unexpected side effects. Using superglobals undermines the effort of using dependency injection and using containers.

The middleware creates an object that wraps `$_SESSION`, which is available for dependency injection and as attribute of the PSR-7 `ServerRequest`. The middleware complies with [PSR-15](https://www.php-fig.org/psr/psr-15/). It will also work as double pass middleware.

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

[](#installation)

```
composer require jasny/session-middleware

```

Usage
-----

[](#usage)

```
use Jasny\Session\SessionMiddleware;

$router->add(new SessionMiddleware());
$response = $router->handle($request);
```

Get the session object from the PSR-7 ServerRequest object and use it as array

```
$session = $request->getAttribute('session');
$session['foo.bar'] = 10;

if (isset($session['foo.user'])) {
  // ...
}
```

The session is started by the middleware.

### Methods

[](#methods)

The session object implements `SessionInterface` and has the following methods;

- `start()` - Start the session.
- `status()` - Get the session status.
- `stop()` - Write session data and end session.
- `abort()` - Discard session array changes and finish session.
- `clear()` - Clear all data from the session.
- `kill()` - Destroy the session and remove the session cookie.
- `rotate()` - Delete the current session and start a new one.

When rotating a session, it's possible to copy some of the data by supplying a callback.

```
$session->rotate(fn(array $oldSessionData) => ['tid' => $oldSessionData['tid'] ?? null]);
```

### Session options

[](#session-options)

By default, the middleware will create a `GlobalSession` object. This object is linked to PHPs session management including `$_SESSION`. You can manually instantiate this object, supplying session options. These options are passed to `session_start()`.

```
use Jasny\Session\GlobalSession;
use Jasny\Session\SessionMiddleware;

$session = new GlobalSession([
    'cookie_lifetime' => 0,
    'cookie_httponly' => 1,
    'use_only_cookies' => 1,
    'use_trans_sid' => 0,
    'cookie_secure' => (bool)($_SERVER['HTTPS'] ?? false),
    'cookie_samesite' => 'Lax',
]);

$router->add(new SessionMiddleware($session));
$response = $router->handle($request);
```

### Flash

[](#flash)

The session flash object can be used to pass a message to the next request. It is automatically removed from the session after it is used. A typical use case is to store information in a database, than redirect to a page and showing a success message. Or if the information could not be saved, to show an error message.

The flash information contains a type (e.g. `success`, `error`, `info`, `warning`) and a message. Optionally a content type can be specified for the message. This defaults to `text/plain`.

```
$session->flash('success', 'The information has been saved');
```

In the next request

```
{% for flash in app.flashes() %}

        {{ flash.message }}

{% endfor %}
```

If `flash()` or `flashes()` is called, the flash messages are cleared from the session. To prevent this call `reissue()`

```
$session->flashes()
    ->reissue()
    ->add('warning', "Could not display the page");

header('Location: /other-page');
exit();
```

Call `$session->flashes()->clear()` to explicly clear all flash messages, both newly added (to the session) and those available for the current request.

Testing
-------

[](#testing)

When running tests, you can injecting a `MockSession` object in the server request before passing it to the middleware.

```
use Jasny\Session\MockSession;

$session = new MockSession([
  'foo.user' => 'john@example.com'
]);

$requestWithSession = $request->withAttribute('session', $session);
$response = $router->handle($requestWithSession);
```

Alternatively you can pass a session object when creating the `SessionMiddleware`. This session object will be used instead of the global session.

```
use Jasny\Session\SessionMiddleware;
use Jasny\Session\MockSession;

$mockSession = new MockSession();

$router->add(new SessionMiddleware($mockSession));
$response = $router->handle($request);
```

###  Health Score

26

—

LowBetter than 43% of packages

Maintenance0

Infrequent updates — may be unmaintained

Popularity19

Limited adoption so far

Community7

Small or concentrated contributor base

Maturity63

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

Total

2

Last Release

2224d ago

PHP version history (2 changes)v1.0.0PHP ~7.1

v1.1.0PHP &gt;=7.4.0

### Community

Maintainers

![](https://www.gravatar.com/avatar/3379a93d51305df325df9045e1a8b205d195e4e8c01312dff53a000ee79002eb?d=identicon)[jasny](/maintainers/jasny)

---

Top Contributors

[![jasny](https://avatars.githubusercontent.com/u/100821?v=4)](https://github.com/jasny "jasny (19 commits)")

---

Tags

phppsr-15session-middlewarepsr-7middlewarepsr-15sessions

### Embed Badge

![Health badge](/badges/jasny-session-middleware/health.svg)

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

###  Alternatives

[mezzio/mezzio

PSR-15 Middleware Microframework

3883.6M97](/packages/mezzio-mezzio)[tuupola/slim-basic-auth

PSR-7 and PSR-15 HTTP Basic Authentication Middleware

4442.0M26](/packages/tuupola-slim-basic-auth)[relay/relay

A PSR-15 server request handler.

3302.1M86](/packages/relay-relay)[tuupola/cors-middleware

PSR-7 and PSR-15 CORS middleware

1331.8M24](/packages/tuupola-cors-middleware)[laminas/laminas-stratigility

PSR-7 middleware foundation for building and dispatching middleware pipelines

586.6M81](/packages/laminas-laminas-stratigility)[middlewares/utils

Common utils for PSR-15 middleware packages

503.4M92](/packages/middlewares-utils)

PHPackages © 2026

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