Session.php Usage Guide

This guide explains how to use Session.php for secure, database-backed PHP sessions, including best practices for session safety.

1. Basic Usage

require_once __DIR__ . '/ExPDO.php';
require_once __DIR__ . '/Session.php';

use Nobanno\ExPDO;
use Nobanno\Session;

$db = new ExPDO("localhost", "database_name", "db_user", "db_pass");
$session = new Session($db);
$session->configure();

After calling $session->configure(), you can use $_SESSION as usual.

2. Setting and Reading Session Variables

if (!isset($_SESSION['test'])) {
    $_SESSION['test'] = 'Hello, session world!';
    echo "Session variable set.";
} else {
    echo "Session variable: ", $_SESSION['test'];
}

3. Best Practices for Security

Tip: Regenerate the session ID after a successful login or privilege change:
// After successful login
$_SESSION['user_id'] = $userId;
session_regenerate_id(true);
Warning: Do not set 'secure' => true unless your site uses HTTPS, or cookies will not be sent.

4. Example: Login Handler

// ... after verifying credentials ...
$_SESSION['user_id'] = $userId;
$_SESSION['role'] = $userRole;
session_regenerate_id(true); // Prevent session fixation

5. Troubleshooting

6. Advanced: Customizing Session Parameters

You can customize session lifetime and other parameters by passing them to the Session constructor or editing Session.php as needed.

7. References

8. Database Table Structure for Sessions

Below is a recommended SQL table structure for storing sessions securely and efficiently in your database. This structure uses utf8mb4 for full Unicode support and is compatible with the Session.php handler.

CREATE TABLE `sessions` (
  `sessionId` varchar(128) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NOT NULL,
  `data` longtext CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL,
  `lastAccess` datetime NULL DEFAULT NULL,
  PRIMARY KEY (`sessionId`) USING BTREE,
  INDEX `idx_lastAccess`(`lastAccess` ASC) USING BTREE
) ENGINE = InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_general_ci ROW_FORMAT=Dynamic;
Tip: Always use the same character set (utf8mb4) for all columns to avoid encoding issues.