This guide explains how to use Session.php for secure, database-backed PHP sessions, including best practices for session safety.
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.
if (!isset($_SESSION['test'])) {
$_SESSION['test'] = 'Hello, session world!';
echo "Session variable set.";
} else {
echo "Session variable: ", $_SESSION['test'];
}
'secure' => true in session_set_cookie_params to ensure cookies are only sent over HTTPS.Session.php to help prevent XSS and CSRF.__DIR__ for require_once to avoid path issues.session_regenerate_id(true); to prevent session fixation.// After successful login
$_SESSION['user_id'] = $userId;
session_regenerate_id(true);
'secure' => true unless your site uses HTTPS, or cookies will not be sent.
// ... after verifying credentials ...
$_SESSION['user_id'] = $userId;
$_SESSION['role'] = $userRole;
session_regenerate_id(true); // Prevent session fixation
You can customize session lifetime and other parameters by passing them to the Session constructor or editing Session.php as needed.
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;
utf8mb4 for maximum compatibility.utf8mb4) for all columns to avoid encoding issues.