Search by

kodhe / session

karyakode

Kodhe Session component

Package info

github.com/kodhe/session

pkg:composer/kodhe/session

Statistics

Installs: 12

Dependents: 1

Suggesters: 0

Stars: 0

Open Issues: 0

1.1.0 2026-09-28 21:44 UTC

This package is not auto-updated.

Last update: 2026-10-28 12:33:08 UTC


README

A modular session package — a refactored version of the CodeIgniter 3 Session library with a PSR-4 namespace (Kodhe\Framework\Session\) and declare(strict_types=1). It remains 100% backward compatible with the CI3 API (userdata(), set_userdata(), flashdata(), etc.) while internally using modern design patterns: driver abstraction, the SessionId value object, and separate managers for flash data, cookies, and storage.

Available drivers: Files (default), Database, Redis, Memcached.

Installation

composer require kodhe/session

Requirements: PHP >= 8.1. Suggested: ext-redis / ext-memcached when using the corresponding drivers.

Quick Start

<?php

declare(strict_types=1);

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

use Kodhe\Framework\Session\Session;

$session = new Session([
    'sess_driver'  => 'files',
    'sess_expiration' => 7200,
]);

// Storing data
$session->set_userdata('user_id', 42);
$session->set_userdata(['name' => 'John', 'role' => 'admin']);

// Reading data
echo $session->userdata('user_id');   // 42
var_dump($session->has_userdata('name')); // true

// Flash data (disappears after one read)
$session->set_flashdata('notice', 'Saved successfully!');
echo $session->flashdata('notice');

// Deleting
$session->unset_userdata('role');
$session->sess_destroy();

Directory Structure

src/
├── Session.php                 # Main class (implements SessionInterface)
├── Driver.php                  # Driver base class
├── HandlerInterface.php
├── Contracts/                  # SessionInterface, StorageInterface, etc.
├── Drivers/                    # FilesDriver, DatabaseDriver, RedisDriver, MemcachedDriver
├── Factory/DriverFactory.php   # Creates drivers based on configuration
├── Flash/FlashDataManager.php  # Flashdata & tempdata logic
├── Storage/                    # SessionStorage, NullStorage
├── Support/                    # SessionConfig, CookieManager, SessionIdGenerator
├── ValueObjects/SessionId.php
└── helpers.php                 # Global helpers (autoloaded via composer "files")

Usage

1. Flashdata & Tempdata

// Flashdata: persists until the next read
$session->set_flashdata('error', 'Email already registered');
$session->keep_flashdata('error');   // extend for one more request

// Tempdata: persists based on a TTL (seconds), default 300
$session->set_tempdata('draft', ['title' => 'Article draft'], ttl: 600);
$draft = $session->tempdata('draft');

2. ID regeneration (anti session fixation)

$session->sess_regenerate(destroy: false); // new ID, old data kept

3. Choosing another driver

$session = new Session([
    'sess_driver'     => 'database',
    'sess_save_path'  => 'ci_sessions',       // table name
    'sess_expiration' => 7200,
]);

// Redis
$session = new Session([
    'sess_driver'    => 'redis',
    'sess_save_path' => 'tcp://127.0.0.1:6379?weight=1',
]);

Storage table for the database driver (MySQL):

CREATE TABLE `ci_sessions` (
    `id`         VARCHAR(128) NOT NULL,
    `ip_address` VARCHAR(45)  NOT NULL,
    `timestamp`  INT UNSIGNED NOT NULL,
    `data`       BLOB NOT NULL,
    PRIMARY KEY (`id`)
);

Required! If the table has not been created yet — or the column names differ from the schema above — the driver throws an Exception with a clear message on the first request ("Session table ... is missing the required column 'data'") instead of the confusing Unknown column 'data' in 'SELECT' error. When migrating from an old CI3 schema that uses the lastactivity column, the expiry column is detected automatically during garbage collection; however the id, ip_address, and data columns are still mandatory. Quick alternative for development: use 'sess_driver' => 'files'.

Configuration (common keys)

Option Type Default Description
sess_driver string files files, database, redis, memcached
sess_expiration int 7200 Session lifetime in seconds
sess_save_path string '' Folder path / table / driver connection
cookie_name string ci_session Session cookie name
cookie_secure bool false Send the cookie over HTTPS only
cookie_httponly bool true Cookie cannot be read by JavaScript

API Reference (Main Class)

Method Description
userdata($key = null) Read one/all session data
set_userdata($data, $value = null) Store data (array or key–value)
unset_userdata($key) Delete data
has_userdata(string $key) Check whether a key exists
all_userdata() All session data as an array
set_flashdata() / flashdata() / keep_flashdata() One-read flash data
set_tempdata() / tempdata() Temporary data based on a TTL
sess_destroy() Destroy the session
sess_regenerate(bool $destroy = false) Regenerate the session ID

CodeIgniter 3 Compatibility

  • All CI3 method names are preserved, including the public $userdata property (a reference to $_SESSION).
  • The helpers in src/helpers.php are loaded automatically via composer files autoload, so the old procedural calling style remains available.

Notes & Limitations

  • The redis/memcached drivers require the corresponding PHP extensions; DriverFactory throws a SessionException if a driver is unavailable.
  • This package is standalone (kodhe/session), but its URL routing helper is provided by the kodhe/http package.

Testing

cd session && composer install && vendor/bin/phpunit

License

MIT. See LICENSE.