-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathPdoSqliteSessionHandler.php
More file actions
177 lines (154 loc) · 5.66 KB
/
PdoSqliteSessionHandler.php
File metadata and controls
177 lines (154 loc) · 5.66 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
<?php
class PdoSqliteSessionHandler implements \SessionHandlerInterface {
private $pdo, $dsn, $table;
public static $dbFilename = 'php_session.sqlite.db';
/**
* Re-initialize existing session, or creates a new one.
* Called when a session starts or when session_start() is invoked.
*
* @param string $savePath The path where to store/retrieve the session.
* @param string $name The session name.
*/
public function open($savePath, $sessionName) {
if (!is_null($this->pdo)) {
throw new \BadMethodCallException('Bad call to open(): connection already opened.');
}
if (!ctype_alnum($sessionName)) {
throw new \InvalidArgumentException('Invalid session name. Must be alphanumeric.');
}
if (false === realpath($savePath)) {
mkdir($savePath, 0700, true);
}
if (!is_dir($savePath) || !is_writable($savePath)) {
throw new \InvalidArgumentException('Invalid session save path.');
}
$dbOptions = [
\PDO::ATTR_ERRMODE => \PDO::ERRMODE_EXCEPTION,
\PDO::ATTR_PERSISTENT => true,
\PDO::ATTR_MAX_COLUMN_LEN => 32,
\PDO::ATTR_EMULATE_PREPARES => false,
\PDO::ATTR_CASE => \PDO::CASE_LOWER,
\PDO::ATTR_CURSOR => \PDO::CURSOR_FWDONLY,
# \PDO::ATTR_AUTOCOMMIT => false,
];
$this->dsn = 'sqlite:'.$savePath.DIRECTORY_SEPARATOR.static::$dbFilename;
$this->pdo = new \PDO($this->dsn, NULL, NULL, $dbOptions);
$this->table = '"'.strtolower($sessionName).'"';
$this->pdo->exec('PRAGMA encoding="UTF-8";');
$this->pdo->exec('PRAGMA auto_vacuum=FULL;');
$this->pdo->exec('PRAGMA locking_mode=EXCLUSIVE;');
$this->pdo->exec('PRAGMA synchronous=FULL;');
$this->pdo->exec('PRAGMA temp_store=MEMORY;');
$this->pdo->exec('PRAGMA secure_delete=1;');
$this->pdo->exec('PRAGMA writable_schema=0;');
$this->pdo->exec(
"CREATE TABLE IF NOT EXISTS {$this->table} (
id TEXT PRIMARY KEY NOT NULL,
data TEXT CHECK (TYPEOF(data) = 'text') NOT NULL DEFAULT '',
time INTEGER CHECK (TYPEOF(time) = 'integer') NOT NULL
) WITHOUT ROWID;"
); # time DEFAULT (strftime('%s', 'now'))
return true;
}
/**
* Closes the current session.
*/
public function close() {
$this->pdo = null;
return true;
}
/**
* Returns an encoded string of the read data.
* If nothing was read, it must return an empty string.
* This value is returned internally to PHP for processing.
*
* @param string $id The session id.
*
* @return string
*/
public function read($id) {
$sql = "SELECT data FROM {$this->table} WHERE id = :id LIMIT 1";
$sth = $this->getDb()->prepare($sql);
$sth->bindParam(':id', $id, \PDO::PARAM_STR);
$sth->execute();
$rows = $sth->fetchAll(\PDO::FETCH_NUM);
return $rows ? base64_decode($rows[0][0]) : '';
}
/**
* Writes the session data to the session storage.
*
* Called by session_write_close(),
* when session_register_shutdown() fails,
* or during a normal shutdown.
*
* close() is called immediately after this function.
*
* @param string $id The session id.
* @param string $data The encoded session data.
*
* @return boolean
*/
public function write($id, $data) {
$sql = "REPLACE INTO {$this->table} (id, data, time) VALUES (:id, :data, :time)";
$sth = $this->getDb()->prepare($sql);
$sth->bindParam(':id', $id, \PDO::PARAM_STR);
$sth->bindValue(':data', base64_encode($data), \PDO::PARAM_STR);
$sth->bindValue(':time', time(), \PDO::PARAM_INT);
return $sth->execute();
}
/**
* Destroys a session.
*
* Called by session_regenerate_id() (with $destroy = TRUE),
* session_destroy() and when session_decode() fails.
*
* @param string $id The session ID being destroyed.
*
* @return boolean
*/
public function destroy($id) {
$sql = "DELETE FROM {$this->table} WHERE id = :id";
$sth = $this->getDb()->prepare($sql);
$sth->bindParam(':id', $id, \PDO::PARAM_STR);
return $sth->execute();
}
/**
* Cleans up expired sessions.
* Called by session_start(), based on session.gc_divisor,
* session.gc_probability and session.gc_lifetime settings.
*
* @param string $lifetime Sessions that have not updated for
* the last `$lifetime` seconds will be removed.
*
* @return boolean
*/
public function gc($lifetime) {
$sql = "DELETE FROM {$this->table} WHERE time < :time";
$sth = $this->getDb()->prepare($sql);
$sth->bindValue(':time', time() - $lifetime, \PDO::PARAM_INT);
return $sth->execute();
}
public function getDb() {
return $this->pdo;
}
public function getDsn() {
return $this->dsn;
}
public function getTable() {
return trim($this->table, '"');
}
public static function register($dbFilename = null) {
$status = session_status();
if (PHP_SESSION_ACTIVE === $status) {
throw new \LogicException('A session is already open.');
} elseif (PHP_SESSION_DISABLED === $status) {
throw new \LogicException('PHP sessions are disabled.');
}
if ($dbFilename) {
static::$dbFileName = $dbFilename;
}
$handler = new static();
session_set_save_handler($handler, true);
return $handler;
}
}