PHPackages                             drnasin/mysql-pdo-secure-session-handler - 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. [Database &amp; ORM](/categories/database)
4. /
5. drnasin/mysql-pdo-secure-session-handler

ActiveLibrary[Database &amp; ORM](/categories/database)

drnasin/mysql-pdo-secure-session-handler
========================================

Mysql secure session handler with openssl encryption of session data and 'per session' based lifetime.

2.0.0(1mo ago)551MITPHPPHP &gt;=8.3CI passing

Since Nov 21Pushed 1mo ago1 watchersCompare

[ Source](https://github.com/drnasin/mysql-pdo-secure-session-handler)[ Packagist](https://packagist.org/packages/drnasin/mysql-pdo-secure-session-handler)[ Docs](https://github.com/drnasin/mysql-pdo-secure-session-handler)[ RSS](/packages/drnasin-mysql-pdo-secure-session-handler/feed)WikiDiscussions master Synced yesterday

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

[![Tests](https://github.com/drnasin/mysql-pdo-secure-session-handler/actions/workflows/tests.yml/badge.svg)](https://github.com/drnasin/mysql-pdo-secure-session-handler/actions/workflows/tests.yml)[![License: MIT](https://camo.githubusercontent.com/fdf2982b9f5d7489dcf44570e714e3a15fce6253e0cc6b5aa61a075aac2ff71b/68747470733a2f2f696d672e736869656c64732e696f2f62616467652f4c6963656e73652d4d49542d79656c6c6f772e737667)](https://opensource.org/licenses/MIT)[![PHP Version](https://camo.githubusercontent.com/c6447a0f34a5721f3e61f5e30bd15977d04dc02ecbcd26efad1c3328d9f864f5/68747470733a2f2f696d672e736869656c64732e696f2f62616467652f5048502d253345253344382e332d3838393242462e737667)](https://php.net)

MySQL PDO Secure Session Handler
================================

[](#mysql-pdo-secure-session-handler)

A production-ready PHP session handler that stores encrypted session data in MySQL using PDO. Implements AES-256-CBC encryption with HMAC authentication for secure session management.

When to Use This Library
------------------------

[](#when-to-use-this-library)

This session handler is ideal for applications that require:

- **Enhanced Security**: Session data is encrypted at rest using AES-256-CBC with per-session initialization vectors (IV)
- **Data Integrity**: HMAC-SHA256 authentication ensures session data hasn't been tampered with
- **Centralized Session Storage**: MySQL-backed sessions work across multiple servers (load-balanced environments)
- **Compliance Requirements**: Applications handling sensitive data (PII, healthcare, financial) needing encrypted session storage
- **Granular Control**: Custom session lifetime management and garbage collection at the database level

Features
--------

[](#features)

### Security

[](#security)

- **AES-256-CBC Encryption**: Industry-standard encryption for all session data
- **Per-Session IV**: Unique initialization vector generated for each session
- **HMAC Authentication**: SHA-256 based message authentication for data integrity verification
- **Constant-Time Comparison**: Protection against timing attacks during HMAC verification

### Performance

[](#performance)

- **Optimized Key Derivation**: Authentication keys calculated once per session lifecycle
- **Database Indexing**: Optimized queries for efficient session cleanup and retrieval
- **Prepared Statements**: SQL injection protection with PDO prepared statements

### Standards Compliance

[](#standards-compliance)

- **PSR-4 Autoloading**: Modern PHP namespace structure
- **SessionHandlerInterface**: Native PHP session handling integration
- **Type Safety**: Full PHP 8.3+ type declarations with readonly classes

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

[](#requirements)

- PHP 8.3 or higher
- PDO extension with MySQL driver
- OpenSSL extension
- MySQL 5.7+ or MariaDB 10.2+

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

[](#installation)

### Via Composer (Recommended)

[](#via-composer-recommended)

```
composer require drnasin/mysql-pdo-secure-session-handler
```

### Manual Installation

[](#manual-installation)

```
git clone https://github.com/drnasin/mysql-pdo-secure-session-handler.git
cd mysql-pdo-secure-session-handler
composer install
```

Quick Start
-----------

[](#quick-start)

### 1. Generate Encryption Key

[](#1-generate-encryption-key)

Generate a secure encryption key (128-256 bits recommended):

```
# Using Composer script
composer gen-key-file

# Or manually
openssl rand -base64 -out ./storage/encryption.key 160
```

### 2. Create Database Table

[](#2-create-database-table)

```
use src\App\EncryptedSessionHandler;

$pdo = new PDO('mysql:host=localhost;dbname=myapp', 'username', 'password');
$encryptionKey = trim(file_get_contents('./storage/encryption.key'));

$handler = new EncryptedSessionHandler($pdo, 'sessions', $encryptionKey);
$handler->createTable();
```

This creates the following table structure:

```
CREATE TABLE sessions (
    session_id VARCHAR(128) NOT NULL PRIMARY KEY,
    modified TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
    session_data MEDIUMTEXT NOT NULL,
    lifetime INT NOT NULL,
    iv VARBINARY(16) NOT NULL,
    INDEX idx_modified_lifetime (modified, lifetime)
) ENGINE=InnoDB;
```

### 3. Configure Session Handler

[](#3-configure-session-handler)

```
use src\App\EncryptedSessionHandler;

// Database connection
$pdo = new PDO(
    'mysql:host=localhost;dbname=myapp;charset=utf8mb4',
    'username',
    'password',
    [
        PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,
        PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC,
        PDO::ATTR_EMULATE_PREPARES => false,
    ]
);

// Load encryption key
$encryptionKey = trim(file_get_contents('./storage/encryption.key'));

// Initialize handler
$handler = new EncryptedSessionHandler($pdo, 'sessions', $encryptionKey);
session_set_save_handler($handler, true);

// Start session with secure settings
session_start([
    'use_strict_mode' => 1,
    'cookie_secure' => 1,      // HTTPS only
    'cookie_httponly' => 1,    // JavaScript cannot access
    'cookie_samesite' => 'Lax' // CSRF protection
]);

// Use sessions normally
$_SESSION['user_id'] = 123;
$_SESSION['username'] = 'john_doe';
```

Usage Examples
--------------

[](#usage-examples)

### Basic Usage

[](#basic-usage)

```
