Skip to content

Instantly share code, notes, and snippets.

@code-boxx
Last active May 26, 2023 02:46
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save code-boxx/78a8cff4a8165970784e8e7e66b452fa to your computer and use it in GitHub Desktop.
Save code-boxx/78a8cff4a8165970784e8e7e66b452fa to your computer and use it in GitHub Desktop.
PHP Database Session

SAVE PHP SESSION IN MYSQL DATABASE

https://code-boxx.com/save-php-session-in-database/

NOTES

  1. Create a dummy database and import 1-db-sess.sql.
  2. Change the database settings in 2-lib-sess.php to your own.
  3. Access 3-demo.php in the browser and verify the session entry in the database.

LICENSE

Copyright by Code Boxx

Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.

CREATE TABLE `sessions` (
`id` varchar(64) NOT NULL,
`access` bigint(20) UNSIGNED DEFAULT NULL,
`data` text DEFAULT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;
ALTER TABLE `sessions`
ADD PRIMARY KEY (`id`);
<?php
// (A) DATABASE SESSION CLASS
class MySess implements SessionHandlerInterface {
// (A1) PROPERTIES
private $pdo = null;
private $stmt = null;
public $error = "";
public $lastID = null;
// (A2) INIT - CONNECT TO DATABASE
public function __construct() {
$this->pdo = new PDO(
"mysql:host=".SDB_HOST.";charset=".SDB_CHAR.";dbname=".SDB_NAME,
SDB_USER, SDB_PASS, [
PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,
PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC
]);
}
// (A3) HELPER - EXECUTE SQL QUERY
function exec ($sql, $data=null) : void {
$this->stmt = $this->pdo->prepare($sql);
$this->stmt->execute($data);
$this->lastID = $this->pdo->lastInsertId();
}
// (A4) SESSION OPEN - NOTHING IN PARTICULAR...
function open ($path, $name) { return true; }
// (A5) SESSION CLOSE - CLOSE DATABASE CONNECTION
function close () {
if ($this->stmt !== null) { $this->stmt = null; }
if ($this->pdo !== null) { $this->pdo = null; }
return true;
}
// (A6) SESSION READ - FETCH FROM DATABASE
function read ($id) {
$this->exec("SELECT `data` FROM `sessions` WHERE `id`=?", [$id]);
$data = $this->stmt->fetchColumn();
return $data===false ? "" : $data ;
}
// (A7) SESSION WRITE - WRITE INTO DATABASE
function write ($id, $data) {
$this->exec("REPLACE INTO `sessions` VALUES (?, ?, ?)", [$id, time(), $data]);
return true;
}
// (A8) SESSION DESTROY - DELETE FROM DATABASE
function destroy ($id) {
$this->exec("DELETE FROM `sessions` WHERE `id`=?", [$id]);
return true;
}
// (A9) GARBAGE COLLECT - DELETE OLD ENTRIES
function gc ($max) {
$this->exec("DELETE FROM `sessions` WHERE `access` < ?", [(time() - $max)]);
return true;
}
}
// (B) DATABASE SETTINGS - CHANGE TO YOUR OWN!
define("SDB_HOST", "localhost");
define("SDB_CHAR", "utf8mb4");
define("SDB_NAME", "test");
define("SDB_USER", "root");
define("SDB_PASS", "");
// (C) START!
session_set_save_handler(new MySess(), true);
session_start();
<?php
require "2-lib-sess.php";
$_SESSION["test"] = time();
print_r($_SESSION);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment