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
| namespace think\session\driver;
use SessionHandlerInterface; use think\Db; use think\Exception; use think\facade\Config;
class Mysql implements SessionHandlerInterface { protected $handler = null; protected $config = [ 'hostname' => '', 'database' => '', 'username' => '', 'password' => '', 'hostport' => '', 'charset' => '', 'expire' => 3600, 'session_name' => '', 'session_table' => '', ]; protected $table_name = null;
public function __construct($config = []) { $this->config = array_merge($this->config, Config::get('database.'), $config); $this->table_name = empty($this->config['session_table']) ? $this->config['prefix'] . '_session' : $this->config['session_table']; }
public function open($savePath, $sessName) { if (empty($this->config['hostname'])) throw new Exception('database config error'); $this->handler = Db::connect($this->config); return true; }
public function close() { $this->gc(ini_get('session.gc_maxlifetime')); $this->handler = null; return true; }
public function read($sessID) { return (string)Db::table($this->table_name)->where([['session_id', '=', $this->config['session_name'] . $sessID], ['session_expire', '>=', time()]])->value('session_data'); }
public function write($sessID, $sessData) { $unserialize_session_data = unserialize(explode('|', $sessData)[1]);
$params = [ 'session_id' => $this->config['session_name'] . $sessID, 'session_expire' => $this->config['expire'] + time(), 'session_data' => $sessData, 'user_name' => $user_name, 'ip' => get_ip(), ];
$sql = "REPLACE INTO {$this->table_name} (session_id,session_expire,session_data,user_name,ip) VALUES (:session_id, :session_expire, :session_data,:user_name,:ip)"; $result = $this->handler->execute($sql, $params); return $result ? true : false; }
public function destroy($sessID) { $result = $this->handler->execute("DELETE FROM {$this->table_name} WHERE session_id = :session_id", ['session_id' => $this->config['session_name'] . $sessID]); return $result ? true : false; }
public function gc($sessMaxLifeTime) { $result = $this->handler->execute("DELETE FROM {$this->table_name} WHERE session_expire < :session_expire", ['session_expire' => time()]); return $result ? true : false; } }
|