1 <?php
2 class session
3 {
4 private static $handle = null;
5 private static $ip = null;
6 private static $lifetime = null;
7 private static $time = null;
8
9 static function init($pdo)
10 {
11 self::$handle = $pdo;
12 self::$ip = !empty($_SERVER["REMOTE_ADDR"]) ? $_SERVER["REMOTE_ADDR"] : "unknow";
13 self::$lifetime = ini_get('session.gc_maxlifetime');
14 self::$time = time();
15 }
16
17 static function start($pdo)
18 {
19 self::init($pdo);
20 session_set_save_handler(
21 array(__CLASS__,'open'),
22 array(__CLASS__,'close'),
23 array(__CLASS__,'read'),
24 array(__CLASS__,'write'),
25 array(__CLASS__,'destroy'),
26 array(__CLASS__,'gc')
27 );
28 session_start();
29 }
30
31 public static function open($path, $name)
32 {
33 return true;
34 }
35
36 public static function close()
37 {
38 return true;
39 }
40
41 public static function read($PHPSESSID)
42 {
43 $sql = "select * from session where PHPSESSID = ?";
44 $smit = self::$handle->prepare($sql);
45 $smit->execute(array($PHPSESSID));
46
47 if(!$result = $smit->fetch(PDO::FETCH_ASSOC))
48 {
49 return '';
50 }
51
52 if(self::$ip != $result['client_ip'])
53 {
54 self::destroy($PHPSESSID);
55 return '';
56 }
57
58 if( ($result['update_time'] + self::$lifetime) < self::$time)
59 {
60 self::destroy($PHPSESSID);
61 return '';
62 }
63
64 return $result['data'];
65 }
66
67 public static function write($PHPSESSID,$data)
68 {
69 $sql = "select * from session where PHPSESSID = ?";
70 $stmt = self::$handle->prepare($sql);
71 $stmt->execute(array($PHPSESSID));
72
73 if($result = $stmt->fetch(PDO::FETCH_ASSOC))
74 {
75 if($result['data'] != $data || self::$time-30 > $result['update_time'])
76 {
77 $sql="update session set update_time = ?, data =? where PHPSESSID = ?";
78 $stmt = self::$handle->prepare($sql);
79 $stmt->execute(array(self::$time,$data,$PHPSESSID));
80 }
81
82
83 }else
84 {
85 if(!empty($data))
86 {
87 $sql="insert into session(PHPSESSID, update_time, client_ip, data) values(?,?,?,?)";
88 $sth = self::$handle->prepare($sql);
89 $sth->execute(array($PHPSESSID,self::$time,self::$ip,$data));
90 }
91 }
92 return true;
93 }
94
95 public static function destroy($PHPSESSID)
96 {
97 $sql = "delete from session where PHPSESSID = ?";
98 $sth = self::$handle->prepare($sql);
99 $sth->execute(array($PHPSESSID));
100 return true;
101 }
102
103 public static function gc($lifetime)
104 {
105 $sql = "delete from session where update_time < ?";
106 $stmt=self::$handler->prepare($sql);
107 $stmt->execute(array(self::$time-self::$lifetime));
108 return true;
109 }
110 }
111
112 try{
113 $pdo = new PDO("mysql:host=localhost;dbname=test", "root" ,"");
114 }catch(PDOException $e)
115 {
116 echo $e->getMessage();
117 }
118
119 session::start($pdo);