//创建表
//create sesslib.sql
CREATE TABLE sesslib (
data text,
time datetime,
id int(11) DEFAULT @#0@# NOT NULL auto_increment,
sid varchar(32) NOT NULL,
PRIMARY KEY (id),
UNIQUE sid (sid)
);
//End
//XX.php自定义了session的数据库路径,当某个页面需要使用//session时,可以include这个部分,使用方法为:
<?
include "XX.php";//XX.php
session_start();
//以下就可以正常使用session了
?>
/******************************************************/
XX.php 内容:
/*****************************************************/
<?
$sess_dbh="";
$sess_maxlifetime=get_cfg_var("session.gc_maxlifetime");
function sess_open($save_path, $session_name) {
global $hostname, $dbusername, $dbpassword, $dbname, $sess_dbh;
//$sess_dbh=mysql_pconnect($hostname,$dbusername,$dbpassword) or die("不能连接数据库!");
$sess_dbh=mysql_pconnect(@#localhost@#,@#test@#,@#test@#) or die("不能连接数据库!");
// mysql_select_db("$dbname") or die("不能选择数据库!");
mysql_select_db(@#test@#) or die("不能选择数据库!");
return(true);
}
function sess_close() {
//mysql_close();
return(true);
}
function sess_read($sid) {
global $sess_dbh;
$result = mysql_query("select data from sesslib where sid=@#$sid@#", $sess_dbh);
$n=mysql_num_rows($result);
if($n==0) {
return("");
}
else {
$sess_data=mysql_result($result,0);
return($sess_data);
}
}
function sess_write($sid, $sess_data) {
global $sess_dbh;
if(!empty($sess_data)){
$r=mysql_query("insert into sesslib set sid=@#$sid@#,data=@#$sess_data@#,time=now()", $sess_dbh);
if(!$r) { // insertion failed, means the session is already there, update it
$r=mysql_query("update sesslib set sid=@#$sid@#, data=@#$sess_data@#, time=now() where sid=@#$sid@#",$sess_dbh);
}
return $r;
}}
function sess_destroy($sid) {
global $sess_dbh;
$r=mysql_query("delete from sesslib where sid=@#$sid@#", $sess_dbh);
return($r);
}
function sess_gc($maxlifetime) {
global $sess_dbh, $sess_maxlifetime;
$r=mysql_query("delete from sesslib where unix_timestamp(now())-unix_timestamp(time)>$sess_maxlifetime", $sess_dbh);
return mysql_affected_rows($sess_dbh);
}
session_set_save_handler("sess_open", "sess_close", "sess_read", "sess_write", "sess_destroy", "sess_gc");
?>
这样一来,安全多了......
延伸阅读
文章来源于领测软件测试网 https://www.ltesting.net/