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

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

pitoncms/session
================

Manage HTTP session state without native PHP sessions

3.1.1(3mo ago)13231AGPL-3.0-or-laterPHPPHP ^7.4 || ^8.0

Since Jan 30Pushed 5d ago2 watchersCompare

[ Source](https://github.com/PitonCMS/Session)[ Packagist](https://packagist.org/packages/pitoncms/session)[ Docs](https://github.com/pitoncms/session)[ RSS](/packages/pitoncms-session/feed)WikiDiscussions master Synced 3d ago

READMEChangelog (5)DependenciesVersions (20)Used By (1)

Piton Session Handler
=====================

[](#piton-session-handler)

This class maintains session state across page views. A hashed, salted session key is set in a cookie which is the key to the session record in a MySQL table. The session key is regenerated every 5 minutes or as set in the configuation array. No information, other than the key, is stored client side. All user session information is kept server side in your database.

When the session starts the session handler looks for a session record matching the cookie key, and if found then runs optional checks to validate the session. If any of the checks fail, or if the session has timed out, the session is destoyed and a new session is started.

Session data can be set and retrieved at any time as either a key-value pair, or an array of key-value pairs. Flash data is also supported, which only persists until the next request.

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

[](#installation)

You can use Composer to install the session handler or just download the files to your project.

### Using Composer

[](#using-composer)

Either require the project in composer,

```
composer require pitoncms/session
```

or modify your `composer.json` project file to require this package and run an update or install.

```
"require": {
  "pitoncms/session": "^3.0.0"
}
```

This will download the files and register the class with the composer autoloader.

### Or Just the Files, Please

[](#or-just-the-files-please)

If you do not use Composer, download this project and unzip. The only file you need is `src/SessionHandler.php`. Place that file in your project and be sure to include it in your startup script.

### Create the Table

[](#create-the-table)

You will need to create the session table in your MySQL database using the **SessionTable.sql** script. You can change the table name in the script if desired, but you will need to provide the table name as a configuration item for `tableName`.

Usage
-----

[](#usage)

To use the session handler create a new instance of `Piton\Session\SessionHandler` passing in a PDO database connection, a configuration array, and an optional logger that implements the `Psr\Log\LoggerInterface`.

### PDO Connection

[](#pdo-connection)

Define a new PDO connection and pass it in as the first argument of the constructor.

```
$dsn = 'mysql:host=' . HOST . ';dbname=' . DBNAME;
$dbh = new PDO($dsn, USERNAME, PASSWORD, DB_OPTIONS);
```

### Define Configuruation

[](#define-configuruation)

Define a configuration array and only include the options you wish to change. The only required configuration option is your application's encryption key. Use a long, random string and do not share it.

**Options**

OptionDefaultDescriptioncookieName'sessionCookie'Your session cookie name.domain''Your primary domain name. If not provided the browser will settableName'session'Name of the MySQL table that stores your sessions.secondsUntilExpiration7200How long before the session expires in seconds.renewalTime300How long before the session key is regenerated in seconds.expireOnClosefalseWhether or not to destroy the session when the browser closes, true or false.checkIpAddressfalseWhether or not to match the IP address to the stored session, true or false.checkUserAgentfalseWhether or not to match the User Agent to the stored session, true or false.secureCookiefalseWhether or not to set cookie when on an HTTPS connection, true or false.salt*none*Your custom encryption key. Any long (16+ characters) string of characters.autoRunSessiontrueWhether to run the session automatically, or only needed.```
$config['salt'] = 'akjfao8ygoa8hba9707lakusdof87'; // Use your own salt, not this one!
$config['secondsUntilExpiration'] = 1800; // 30 minutes. Can also use 60*60*24 to specify 1 day

// Other configuration options ...
```

### Creating a Session

[](#creating-a-session)

Create a new session as part of your application flow.

```
$Session = new Piton\Session\SessionHandler($dbh, $config, $logger);
```

The session runs immediately if `autoRunSession` is set to true (which is the default) and checks for a valid session, regenerates the session key if necessary, and loads any existing session data for immediate retrieval. Create the session object once, or simply add it to your Dependency Injection Container as a singleton.

When the session runs, it queries the database. If you need to make the session class available but do not need to immediately run the session you can set autoRunSession to false in the configuration. Then when you are ready to run a session call the `run()` method.

```
$Session->run();
```

### Save Session Data

[](#save-session-data)

Once the session is running, you can add or update session data by passing in key-value pairs or an array of key-value pairs using the `setData()` method. The value can be any type as long as it is serializable to JSON.

```
// Save simple key-value pair
$Session->setData('lupine', 'wolf');

// Save array of key-value pairs
$sessionData = array(
  'feline' => 'cat',
  'canine' => 'dog',
  'lastModified' => 1422592486
);
$Session->setData($sessionData);
```

Supplying the same key will overwrite any prior value saved in session.

### Get Session Data

[](#get-session-data)

To get session data pass in the item key to `getData()`. The method returns `null` if no key was found. To get all session data simply do not provide an argument.

```
// Get one session item
$value = $Session->getData('keyName');

// Get all session items
$values = $Session->getData();
```

### Save Flash Data

[](#save-flash-data)

Flash data will only stay until the next request, after which it is removed automatically.

You can add flash data by passing in a string, a key-value pair, or an array of key-value pairs using the `setFlashData()` method. The value can be any type as long as it is serializable to JSON.

```
// Save simple key-value pair
$Session->setFlashData('Something went wrong!');
$Session->setFlashData('alert', 'Something went very wrong!');
```

### Get Flash Data

[](#get-flash-data)

To get flash data pass in the item key to `getFlashData()`. The method returns `null` if no key was found. To get all flash data simply do not provide an argument. Flash data is automatically removed on the next request, so there's no need to explicitly unset flash data.

```
// Get one flash item
$value = $Session->getFlashData('alert');

// Get all flash items
$values = $Session->getFlashData();
```

### Unset Session Data

[](#unset-session-data)

You can delete a session item by passing in the item key to `unsetData()`, or delete all session data by not providing an argument.

```
// Delete one session item
$Session->unsetData('keyName');

// Delete all session data
$Session->unsetData();
```

### Delete a Session

[](#delete-a-session)

Any session that does not pass validation will be destoyed automatically. But, if you want to delete the current session call the `destroy()` method.

```
$Session->destroy();
```

WARNING
=======

[](#warning)

Use this session class at your own risk. Read the code, and understand what it does if you intend on using this for for anything secure. We make no warranty if something goes wonky.

###  Health Score

52

—

FairBetter than 96% of packages

Maintenance91

Actively maintained with recent releases

Popularity14

Limited adoption so far

Community10

Small or concentrated contributor base

Maturity77

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

Recently: every ~461 days

Total

18

Last Release

99d ago

Major Versions

1.3.1 → 2.0.02020-02-01

2.1.5 → 3.0.02026-01-13

PHP version history (6 changes)1.0.0PHP &gt;=5.3.0

1.3.0PHP &gt;=5.4

2.0.0PHP &gt;=7.1

2.1.4PHP &gt;=7.3

3.0.0PHP &gt;=8.3

3.1.1PHP ^7.4 || ^8.0

### Community

Maintainers

![](https://avatars.githubusercontent.com/u/39494878?v=4)[PitonCMS](/maintainers/PitonCMS)[@PitonCMS](https://github.com/PitonCMS)

---

Top Contributors

[![wolfmoritz](https://avatars.githubusercontent.com/u/2895080?v=4)](https://github.com/wolfmoritz "wolfmoritz (58 commits)")

---

Tags

sessionsessionspitonpitoncmssession state

### Embed Badge

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

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

###  Alternatives

[nette/http

🌐 Nette Http: abstraction for HTTP request, response and session. Provides careful data sanitization and utility for URL and cookies manipulation.

48619.2M541](/packages/nette-http)[aplus/app

Aplus Framework App Project

5951.6M1](/packages/aplus-app)[mezzio/mezzio-session

Session container and middleware for PSR-7 applications

24982.3k16](/packages/mezzio-mezzio-session)[kdyby/fake-session

FakeSession class for Nette Framework

11354.8k7](/packages/kdyby-fake-session)[mrclay/shibalike

Provides a PHP library for emulating a Shibboleth environment.

2060.5k7](/packages/mrclay-shibalike)[middlewares/php-session

Middleware to start php sessions using the request data

1525.8k3](/packages/middlewares-php-session)

PHPackages © 2026

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