4 * A PHP session handler using PDO to keep session data within a MySQL database
6 * @author Jan Lohage <info@j2l4e.de>
7 * @link https://github.com/j2L4e/PHP-PDO-MySQL-Session-Handler
10 * Based on PHP-MySQL-Session-Handler (uses mysqli)
12 * @author Manuel Reinhard <manu@sprain.ch>
13 * @link https://github.com/sprain/PHP-MySQL-Session-Handler
17 use SessionHandlerInterface;
19 class SessionHandler implements SessionHandlerInterface
22 * a PDO connection resource
29 * the name of the DB table which handles the sessions
36 * Set db data if no connection is being injected
37 * @param string $dbHost
38 * @param string $dbUser
39 * @param string $dbPassword
40 * @param string $dbDatabase
41 * @param string $dbCharset optional, default 'utf8'
43 public function setDbDetails($dbHost, $dbUser, $dbPassword, $dbDatabase, $dbCharset = 'utf8') {
45 //create db connection
46 $this->dbh = new PDO("mysql:" .
48 "dbname={$dbDatabase};" .
49 "charset={$dbCharset}",
53 PDO::ATTR_EMULATE_PREPARES => false,
54 PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION //USE ERRMODE_SILENT FOR PRODUCTION!
61 * Inject PDO from outside
62 * @param object $dbh expects PDO object
64 public function setPDO($dbh) {
70 * Set MySQL table to work with
71 * @param string $dbTable
73 public function setDbTable($dbTable) {
74 $this->dbTable = $dbTable;
82 public function open($save_path, $session_name) {
83 //delete old session handlers
84 $limit = time() - (3600 * 24);
85 $stmt = $this->dbh->prepare("DELETE FROM {$this->dbTable} WHERE timestamp < :limit");
86 $ret = $stmt->execute(array(':limit' => $limit));
95 public function close() {
101 * @param int session id
102 * @return string string of the sessoin
104 public function read($id) {
105 $stmt = $this->dbh->prepare("SELECT * FROM {$this->dbTable} WHERE id=:id");
106 $stmt->execute(array(':id' => $id));
108 $session = $stmt->fetch(PDO::FETCH_ASSOC);
111 $ret = $session['data'];
122 * @param int session id
123 * @param string data of the session
125 public function write($id, $data) {
126 $stmt = $this->dbh->prepare("REPLACE INTO {$this->dbTable} (id,data,timestamp) VALUES (:id,:data,:timestamp)");
127 $ret = $stmt->execute(
130 'timestamp' => time()
137 * Destroy the session
138 * @param int session id
141 public function destroy($id) {
142 $stmt = $this->dbh->prepare("DELETE FROM {$this->dbTable} WHERE id=:id");
143 $ret = $stmt->execute(array(
153 * @param int life time (sec.)
155 * @see session.gc_divisor 100
156 * @see session.gc_maxlifetime 1440
157 * @see session.gc_probability 1
158 * @usage execution rate 1/100
159 * (session.gc_probability/session.gc_divisor)
161 public function gc($max) {
162 $stmt = $this->dbh->prepare("DELETE FROM {$this->dbTable} WHERE timestamp < :limit");
163 $ret = $stmt->execute(array(':limit' => time() - intval($max)));