· 8 years ago · May 16, 2018, 10:38 PM
1<?php
2
3
4/**
5
6Database stracture:
7
8CREATE TABLE IF NOT EXISTS `sessions` (
9 `id` varchar(32) NOT NULL,
10 `data` text,
11 `timestamp` int(10) unsigned DEFAULT NULL,
12 PRIMARY KEY (`id`)
13) ENGINE=MyISAM DEFAULT CHARSET=utf8;
14
15
16*/
17
18
19
20
21
22
23class session
24{
25
26 /**
27 * a database connection resource
28 * @var resource
29 */
30 private $_sess_db;
31
32 /**
33 * Open the session
34 * @return bool
35 */
36 public function open() {
37
38 if ($this->_sess_db = mysql_connect('localhost',
39 'root',
40 '')) {
41 return mysql_select_db('sessions', $this->_sess_db);
42 }
43 return false;
44
45 }
46
47
48
49 /**
50 * Close the session
51 * @return bool
52 */
53 public function close() {
54
55 return mysql_close($this->_sess_db);
56
57 }
58
59 /**
60 * Read the session
61 * @param int session id
62 * @return string string of the sessoin
63 */
64 public function read($id) {
65
66 $id = mysql_real_escape_string($id);
67 $sql = sprintf("SELECT `data` FROM `sessions` " .
68 "WHERE id = '%s'", $id);
69 if ($result = mysql_query($sql, $this->_sess_db)) {
70 if (mysql_num_rows($result)) {
71 $record = mysql_fetch_assoc($result);
72 return $record['data'];
73 }
74 }
75 return '';
76
77 }
78
79 /**
80 * Write the session
81 * @param int session id
82 * @param string data of the session
83 */
84 public function write($id, $data) {
85
86 $sql = sprintf("REPLACE INTO `sessions` VALUES('%s', '%s', '%s')",
87 mysql_real_escape_string($id),
88 mysql_real_escape_string($data),
89 mysql_real_escape_string(time()));
90 return mysql_query($sql, $this->_sess_db);
91
92 }
93
94 /**
95 * Destoroy the session
96 * @param int session id
97 * @return bool
98 */
99 public function destroy($id) {
100
101 $sql = sprintf("DELETE FROM `sessions` WHERE `id` = '%s'", $id);
102 return mysql_query($sql, $this->_sess_db);
103
104}
105
106 /**
107 * Garbage Collector
108 * @param int life time (sec.)
109 * @return bool
110 * @see session.gc_divisor 100
111 * @see session.gc_maxlifetime 1440
112 * @see session.gc_probability 1
113 * @usage execution rate 1/100
114 * (session.gc_probability/session.gc_divisor)
115 */
116 public function gc($max) {
117
118 $sql = sprintf("DELETE FROM `sessions` WHERE `timestamp` < '%s'",
119 mysql_real_escape_string(time() - $max));
120 return mysql_query($sql, $this->_sess_db);
121
122 }
123
124}
125
126//ini_set('session.gc_probability', 50);
127//ini_set('session.save_handler', 'user');
128
129$session = new session();
130session_set_save_handler(array($session, 'open'),
131 array($session, 'close'),
132 array($session, 'read'),
133 array($session, 'write'),
134 array($session, 'destroy'),
135 array($session, 'gc'));
136
137// below sample main
138session_write_close();
139session_start();
140//session_regenerate_id(true);
141
142if (isset($_SESSION['counter'])) {
143 $_SESSION['counter']++;
144} else {
145 $_SESSION['counter'] = 1;
146}
147
148echo $_SESSION['counter'];
149
150?>