PHPackages                             switch/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. switch/session

ActiveLibrary

switch/session
==============

High-performance session, cookie, flash, and CSRF protection package for the Switch Framework

00PHP

Since Aug 14Pushed todayCompare

[ Source](https://github.com/celionatti/switch-session)[ Packagist](https://packagist.org/packages/switch/session)[ RSS](/packages/switch-session/feed)WikiDiscussions master Synced today

READMEChangelogDependenciesVersions (2)Used By (0)

Switch Session (`switch/session`)
=================================

[](#switch-session-switchsession)

[![Latest Version](https://camo.githubusercontent.com/34e695c6016bc2a934a96bed696e29b2f2ab562a7134d65a55d00653cd506bea/68747470733a2f2f696d672e736869656c64732e696f2f62616467652f76657273696f6e2d312e302e302d626c75652e737667)](https://github.com/celionatti/switch-session)[![License](https://camo.githubusercontent.com/8bb50fd2278f18fc326bf71f6e88ca8f884f72f179d3e555e20ed30157190d0d/68747470733a2f2f696d672e736869656c64732e696f2f62616467652f6c6963656e73652d4d49542d677265656e2e737667)](LICENSE)[![PHP](https://camo.githubusercontent.com/d7583679f2fa23bc68186b2e772180e9fbd9afb79c983dff6b928e19d389aae8/68747470733a2f2f696d672e736869656c64732e696f2f62616467652f5048502d253345253344382e322d3737376262342e737667)](https://php.net)

**Switch Session** is an ultra-fast, standalone session, cookie, flash message, and CSRF protection package for the **Switch Framework** and any modern PHP application.

---

⚡ Key Features
--------------

[](#-key-features)

- 🍪 **Fluent Cookie API (`Cookie`, `CookieJar`)**: Immutable cookie builder with RFC 6265 compliance (`SameSite`, `HttpOnly`, `Secure`, `Partitioned / CHIPS`).
- 🗄️ **Multi-Driver Storage**:
    - `file` (Default): Atomic file-based session store with automatic garbage collection.
    - `database`: High-concurrency session persistence using `switch/database` / PDO.
    - `cookie`: Encrypted client-side session payload.
    - `array`: Lightning-fast in-memory session driver for unit tests.
- ⚡ **Flash Messages Engine**: Automatic single-request flash state with `flash()`, `now()`, `keep()`, and `reflash()`.
- 🛡️ **CSRF Protection**: Time-constant secure token verification (`VerifyCsrfToken` PSR-15 middleware) and helper `{!! csrf_field() !!}`.
- 🚀 **PSR-15 Middleware**: Seamless integration with PSR-7 (`ServerRequestInterface`, `ResponseInterface`).

---

📦 Installation
--------------

[](#-installation)

```
composer require switch/session
```

---

🚀 Quick Usage
-------------

[](#-quick-usage)

### 1. Basic Session Interaction

[](#1-basic-session-interaction)

```
use Switch\Session\Session;

// Put data (supports nested dot-notation)
Session::put('user.id', 42);
Session::put('theme', 'dark');

// Retrieve data
$userId = Session::get('user.id');
$theme = Session::get('theme', 'light');

// Check existence
if (Session::has('user.id')) {
    // ...
}

// Flash data for next request
Session::flash('status', 'Profile successfully updated!');

// Pull (get and delete)
$token = Session::pull('temp_token');

// Regenerate Session ID (on login/logout)
Session::regenerate();
```

---

### 2. Global Helpers

[](#2-global-helpers)

```
// Get / Put via helper
session(['cart.total' => 199.99]);
$total = session('cart.total', 0.0);

// CSRF Helpers in views
echo csrf_field(); //
$token = csrf_token();

// Cookie helper
cookie('theme', 'dark', 60); // Queued for 60 minutes
```

---

### 3. PSR-15 Middleware Pipeline

[](#3-psr-15-middleware-pipeline)

Add `StartSession` and `VerifyCsrfToken` to your application's middleware stack:

```
use Switch\Session\Middleware\StartSession;
use Switch\Session\Middleware\VerifyCsrfToken;

$app->withMiddleware(function ($middleware) {
    $middleware->web([
        StartSession::class,
        VerifyCsrfToken::class,
    ]);
});
```

---

### 4. Flash Messages &amp; UI Toasts

[](#4-flash-messages--ui-toasts)

#### Setting Flash Messages (In Controllers or Code)

[](#setting-flash-messages-in-controllers-or-code)

```
// Fluent API
flash()->success('Profile updated successfully!', 'Success');
flash()->error('Payment verification failed.', 'Error');
flash()->warning('Your plan will expire in 3 days.');
flash()->info('Maintenance scheduled tonight.');

// Or quick helper
flash('success', 'Changes saved!');

// In Controllers
$this->flash('success', 'Profile updated!');
$this->flash()->error('Invalid credentials');
```

#### Displaying Flash Messages in Views

[](#displaying-flash-messages-in-views)

```

@flash
```

#### Automatic Switch Live SPA Reactivity

[](#automatic-switch-live-spa-reactivity)

When using `switch/live`, calling `flash('success', '...')` during an SPA request automatically triggers client-side toast notifications without requiring a full page refresh!

---

### 5. Customizing Excluded CSRF Routes

[](#5-customizing-excluded-csrf-routes)

```
class CustomVerifyCsrfToken extends \Switch\Session\Middleware\VerifyCsrfToken
{
    protected array $except = [
        'stripe/webhook',
        'api/*',
    ];
}
```

---

🧪 Testing
---------

[](#-testing)

```
composer test
```

---

📄 License
---------

[](#-license)

The Switch Session package is open-source software licensed under the [MIT license](LICENSE).

###  Health Score

21

—

LowBetter than 17% of packages

Maintenance65

Regular maintenance activity

Popularity0

Limited adoption so far

Community6

Small or concentrated contributor base

Maturity13

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.

### Community

Maintainers

![](https://avatars.githubusercontent.com/u/68065074?v=4)[Celio Natti](/maintainers/celionatti)[@celionatti](https://github.com/celionatti)

---

Top Contributors

[![celionatti](https://avatars.githubusercontent.com/u/68065074?v=4)](https://github.com/celionatti "celionatti (2 commits)")

### Embed Badge

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

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

PHPackages © 2026

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