· 9 years ago · May 04, 2017, 03:16 PM
1<?php
2
3/*
4
5MySQL Session storage. Designed to work with the following table:
6
7CREATE TABLE IF NOT EXISTS `phpsessions` (
8 `SESSID` int(11) NOT NULL,
9 `data` text CHARACTER SET utf8 NOT NULL,
10 `last` int(11) NOT NULL,
11 UNIQUE KEY `SESSID` (`SESSID`)
12) ENGINE=MyISAM DEFAULT CHARSET=utf8;
13
14`last` is a unix timestamp, hence INT.
15
16Take note that in it's current form this system wont support hexadecimal session IDs, which mean the default
17IDs, assigned by PHP will be trimmed. This is done, because SESSID has to be a unique column, and this is only
18achievable with columns of type INT. If you wish to employ a TEXT column, you'll have to modify the _write
19function to accomodate detection of existing records other than ON DUPLICATE UPDATE, since this only works with
20unique fields.
21
22Fucntion names are self-explanatory.
23
24Debugging mode is enabled, uncomment the specified lines in order to disable it.
25
26*/
27
28ini_set('session.gc_probability', 1); // Set to 1000 to make sure cleanup fires every time
29ini_set('session.gc_divisor', 1000);
30ini_set('session.gc_maxlifetime', 1440); // Reduce to see cleanup in action
31
32
33// Main config function (of sorts)
34function __DB($string)
35{
36 // Set access credentials
37 $db_host = "yourhost";
38 $db_user = "yourname";
39 $db_pass = "yourpass";
40 $db_name = "database"; // Database name
41 switch($string)
42 {
43 case "host":
44 return $db_host;
45 case "user":
46 return $db_user;
47 case "pass":
48 return $db_pass;
49 case "name":
50 return $db_name;
51 }
52 return '';
53}
54
55### BEGIN CUSTOM SESSION RECORDING FUNCTIONS ##################################################
56
57function _open($sess_path, $sess_name)
58{
59 // Since a session is openned on every page load, you might want to disable this anyway
60 // Output debug information to a file, uncomment next line to disable
61 // /*
62 $file=fopen("debug.txt","a");
63 $ostring = time() . " :: Openning session\n";
64 fwrite($file,$ostring);
65 fclose($file);
66 // */
67
68 // Must always return true; if persistent connections are possible, setup the use of one here
69 // You may also generate your own ID here, just make sure it's compatible with the var type of the db column
70 // Since the sonctructor takes two parameters, you may want to use them, in case you forked your code to use
71 // several locations to store diffirent sessions or for whatever crazy reason you might. Don't remove them
72 // From the paramether list, though, it will break things
73 return true;
74}
75
76function _close()
77{
78 // Output debug information to a file, uncomment next line to disable
79 // /*
80 $file=fopen("debug.txt","a");
81 $ostring = time() . " :: Closing session\n";
82 fwrite($file,$ostring);
83 fclose($file);
84 // */
85
86 // Must always return true; take into account the use of persistent connections here
87 return true;
88}
89
90function _read($id)
91{
92 // Open connection to database
93 $_sess_db = mysql_connect(__DB("host"), __DB("user"), __DB("pass"));
94 mysql_select_db(__DB("name"), $_sess_db);
95 // Make sure data is properly escaped and not mangled by the ini settings
96 if(get_magic_quotes_gpc()) $id = stripslashes($id);
97 $id = mysql_real_escape_string($id);
98
99 $last = time();
100 $data = '';
101
102 // Get requested data
103 $result = mysql_query("SELECT * FROM `phpsessions` WHERE `SESSID` = '{$id}'");
104 while($sess_data = mysql_fetch_array($result))
105 {
106 $data = $sess_data['data'];
107 }
108 mysql_close($_sess_db);
109
110 // Output debug information to a file, uncomment next line to disable
111 // /*
112 $file=fopen("debug.txt","a");
113 $ostring = time() . " :: READ << ID: {$id} :: Data: {$data}\n";
114 fwrite($file,$ostring);
115 fclose($file);
116 // */
117
118 // Resulting data is a serialized array, which is exactly what we need. Do not process it, PHP takes care of everything.
119 return $data;
120}
121
122function _write($id, $data)
123{
124 // Open connection to database
125 $_sess_db = mysql_connect(__DB("host"), __DB("user"), __DB("pass"));
126 mysql_select_db(__DB("name"), $_sess_db);
127 // Make sure data is properly escaped and not mangled by the ini settings
128 if(get_magic_quotes_gpc())
129 {
130 $id = stripslashes($id);
131 $data = stripslashes($data);
132 }
133 $id = mysql_real_escape_string($id);
134 $data = mysql_real_escape_string($data);
135
136 $last = time();
137
138 // Modify database; PHP gives us a serialized array to begin with, so we're cool without processing it.
139 $result = mysql_query("
140 INSERT INTO `phpsessions` (`SESSID`,`data`,`last`)
141 VALUES ('{$id}','{$data}','{$last}')
142 ON DUPLICATE KEY UPDATE
143 `data` = '{$data}',
144 `last` = '{$last}'
145 ");
146 mysql_close($_sess_db);
147
148 // Output debug information to a file, uncomment next line to disable
149 ### NOTE: Changes to the database wont be visible in the debug until the database is flushed. The database, however, will change in real time ###
150 // /*
151 $file=fopen("debug.txt","a");
152 $ostring = time() . " :: WRITE >> ID: {$id} :: Data: {$data}\n";
153 fwrite($file,$ostring);
154 fclose($file);
155 // */
156
157 return $result;
158}
159
160function _destroy($id)
161{
162 // Output debug information to a file, uncomment next line to disable
163 // /*
164 $file=fopen("debug.txt","a");
165 $ostring = time() . " :: Destroying session: {$id}\n";
166 fwrite($file,$ostring);
167 fclose($file);
168 // */
169
170 // Open connection to database
171 $_sess_db = mysql_connect(__DB("host"), __DB("user"), __DB("pass"));
172 mysql_select_db(__DB("name"), $_sess_db);
173 // Make sure data is properly escaped and not mangled by the ini settings
174 if(get_magic_quotes_gpc()) $id = stripslashes($id);
175 $id = mysql_real_escape_string($id);
176
177 // Preform requested operation
178 $result = mysql_query("DELETE FROM `phpsessions` WHERE `id` = '{$id}'");
179 mysql_close($_sess_db);
180 return $result;
181}
182
183function _clean($max)
184{
185 // Open connection to database
186 $_sess_db = mysql_connect(__DB("host"), __DB("user"), __DB("pass"));
187 mysql_select_db(__DB("name"), $_sess_db);
188 // Determine deletion treshhold
189 $max = (int)$max;
190 $old = time() - $max;
191
192 // Finalize cleanup
193 $result = mysql_query("DELETE FROM `phpsessions` WHERE `last` < '{$old}'");
194 mysql_close($_sess_db);
195
196 // Output debug information to a file, uncomment next line to disable
197 // /*
198 $file=fopen("debug.txt","a");
199 $ostring = time() . " :: Cleaning up sessions older than: {$old}\n";
200 fwrite($file,$ostring);
201 fclose($file);
202 // */
203
204 return $result;
205}
206
207// Initialize our custom handler; you might want this at the beginning of the file, but it might cause problems
208session_set_save_handler('_open',
209 '_close',
210 '_read',
211 '_write',
212 '_destroy',
213 '_clean');
214
215
216### END CUSTOM SESSION RECORDING FUNCTIONS ###################################################
217
218?>