-
Notifications
You must be signed in to change notification settings - Fork 4
/
Copy pathPdoSessionHandler.php
92 lines (70 loc) · 2.65 KB
/
PdoSessionHandler.php
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
<?php namespace Rakit\Session;
use SessionHandlerInterface;
use PDO;
class PdoSessionHandler implements SessionHandlerInterface {
protected $connection;
protected $tablename;
protected $configs;
public function __construct(PDO $connection, $tablename = 'sessions', array $configs = array()) {
$this->connection = $connection;
$this->tablename = $tablename;
$this->configs = array_merge(array('col_sessid' => 'sess_id', 'col_data' => 'sess_data', 'col_last_activity' => 'last_activity'), $configs);
}
public function open($save_path, $sess_name) {
return true;
}
public function read($sess_id) {
$table = $this->tablename;
$col_sessid = $this->configs['col_sessid'];
$col_data = $this->configs['col_data'];
$query = $this->connection->query("
SELECT * FROM {$table}
WHERE {$col_sessid} = '$sess_id'
LIMIT 1
");
$session = $query->fetch(PDO::FETCH_ASSOC);
$this->exists = (false === empty($session));
return $this->exists ? base64_decode($session[$col_data]) : '';
}
public function write($sess_id, $data) {
$table = $this->tablename;
$col_sessid = $this->configs['col_sessid'];
$col_data = $this->configs['col_data'];
$col_la = $this->configs['col_last_activity'];
$data = base64_encode($data);
$time = time();
if ($this->exists) {
$this->connection->query("
UPDATE {$table}
SET
{$col_data} = '{$data}',
{$col_la} = {$time}
WHERE {$col_sessid} = '{$sess_id}'
");
}
else {
$this->connection->query("
INSERT INTO {$table}
({$col_sessid}, {$col_data}, {$col_la})
VALUES ('{$sess_id}','{$data}', {$time})
");
}
$this->exists = true;
}
public function close() {
return true;
}
public function destroy($sess_id) {
$table = $this->table;
$col_sessid = $this->configs['col_sessid'];
$this->connection->query("DELETE FROM {$table} WHERE {$col_sessid}='{$sess_id}'");
return true;
}
public function gc($lifetime) {
$table = $this->table;
$col_la = $this->configs['col_last_activity'];
$expired_time = time() - $lifetime;
$this->connection->query("DELETE FROM {$table} WHERE {$col_la} <= {$expired_time}");
return true;
}
}