PHP数据库存储session

Standard

First up, we need to create a table to handle the session data, and here’s how it will look:
CREATE TABLE sessions (ID INT NOT NULL AUTO_INCREMENT PRIMARY KEY, SessionID CHAR(26), Data TEXT DEFAULT ”, DateTouched INT);

Now, session operations script:

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
mysql_connect("localhost", "phpuser", "alm65z");
mysql_select_db("phpdb");
function sess_open($sess_path, $sess_name) {
return true;
}
function sess_close() {
return true;
}
function sess_read($sess_id) {
$result = mysql_query("SELECT Data FROM sessions WHERE SessionID = '$sess_id';");
if (!mysql_num_rows($result)) {
$CurrentTime = time();
mysql_query("INSERT INTO sessions (SessionID, DateTouched) VALUES ('$sess_id', $CurrentTime);");
return '';
} else {
extract(mysql_fetch_array($result), EXTR_PREFIX_ALL, 'sess');
mysql_query("UPDATE sessions SET DateTouched = $CurrentTime WHERE SessionID = '$sess_id';");
return $sess_Data;
}
}
function sess_write($sess_id, $data) {
$CurrentTime = time();
mysql_query("UPDATE sessions SET Data = '$data', DateTouched = $CurrentTime WHERE SessionID = '$sess_id';");
return true;
}
function sess_destroy($sess_id) {
mysql_query("DELETE FROM sessions WHERE SessionID = '$sess_id';");
return true;
}
function sess_gc($sess_maxlifetime) {
$CurrentTime = time();
mysql_query("DELETE FROM sessions WHERE DateTouched + $sess_maxlifetime < $CurrentTime;");
return true;
}
session_set_save_handler("sess_open", "sess_close", "sess_read", "sess_write", "sess_destroy", "sess_gc");
session_start();
$_SESSION['foo'] = "bar";
$_SESSION['baz'] = "wombat";
?>
 
Next, just file store:
function sess_open($sess_path, $sess_name) {
print "Session opened.\n";
print "Sess_path: $sess_path\n";
print "Sess_name: $sess_name\n\n";
return true;
}
function sess_close() {
print "Session closed.\n";
return true;
}
function sess_read($sess_id) {
print "Session read.\n";
print "Sess_ID: $sess_id\n";
return '';
}
function sess_write($sess_id, $data) {
print "Session value written.\n";
print "Sess_ID: $sess_id\n";
print "Data: $data\n\n";
return true;
}
function sess_destroy($sess_id) {
print "Session destroy called.\n";
return true;
}
function sess_gc($sess_maxlifetime) {
print "Session garbage collection called.\n";
print "Sess_maxlifetime: $sess_maxlifetime\n";
return true;
}
session_set_save_handler("sess_open", "sess_close", "sess_read", "sess_write", "sess_destroy", "sess_gc");
session_start();
$_SESSION['foo'] = "bar";
print "Some text\n";
$_SESSION['baz'] = "wombat";
?>