将SESSION数据放在数据库中,首先建立数据库表:
CREATE TABLE sessions (
session_id varchar(32) NOT NULL,
session_last_access int(10) unsigned,
session_data text,
PRIMARY KEY (session_id)
session_id为主键,保存SESSION ID ,session_last_access是SESSION最后更新时间,session_data是SESSION数据。
PHP 提供了session_set_save_handle() 函数,可以用此函数自定义 SESSION 的处理过程,当然首先要先将 session.save_handler 改成 user,可在 PHP 中进行设置:
接下来着重讲一下 session_set_save_handle() 函数,此函数有六个参数:
session_set_save_handler ( string open, string close, string read, string write, string destroy, string gc )
各个参数为各项操作的函数名,这些操作依次是:打开、关闭、读取、写入、销毁、垃圾回收。PHP 手册中有详细的例子,详细代码如下:
$gb_DBHOSTname = "127.0.0.1"; //主机的名称或是IP地址
$gb_DBname = "dbname"; //数据库名称
$gb_DBuser = "username"; //数据库用户名称
$gb_DBpass = "pwd"; //数据库密码
$gb_COOKIE_DOMAIN = '.a.com';
$SESS_DBH = "";
$SESS_LIFE = get_cfg_var("session.gc_maxlifetime"); //得到session的最大有效期。
session_id(); //不使用 GET/POST 变量方式
ini_set('session.use_trans_sid', 0); //设置垃圾回收最大生存时间
ini_set('session.gc_maxlifetime', 13600); //使用 COOKIE 保存 SESSION ID 的方式
ini_set('session.use_cookies', 1);
ini_set('session.cookie_path', '/'); //多主机共享保存 SESSION ID 的 COOKIE
ini_set("session.cookie_domain", $gb_COOKIE_DOMAIN);
//将 session.save_handler 设置为 user,而不是默认的 files session_module_name('user');
function sess_open($save_path, $session_name) {
global $gb_DBHOSTname, $gb_DBname, $gb_DBuser, $gb_DBpass, $SESS_DBH;
if (!$SESS_DBH = mysql_pconnect($gb_DBHOSTname, $gb_DBuser, $gb_DBpass)) {
die('MySQL Error');
}
mysql_query("SET character_set_connection=utf8, character_set_results=utf8, character_set_client=binary", $SESS_DBH);
if (!mysql_select_db($gb_DBname, $SESS_DBH)) {
die('MySQL Error');
}
return true;
}
function sess_close() {
global $SESS_DBH;
//$SESS_DBH->Close();
return true;
}
function sess_read($key) {
global $SESS_DBH, $SESS_LIFE;
// var_dump($SESS_DBH);
$qry = "select session_data from sessions where session_id = '$key' ";
$qid = mysql_query($qry, $SESS_DBH);
// var_dump($qid);
if (list ($value) = mysql_fetch_row($qid)) {
return $value;
}
return false;
}
function sess_write($key, $val) {
global $SESS_DBH, $SESS_LIFE;
$session_last_access = time();
$value = $val;
$qry = "insert into sessions values('$key',$session_last_access,'$value')";
$qid = mysql_query($qry, $SESS_DBH);
if (!$qid) {
$qry = "update sessions set session_last_access=$session_last_access, session_data='$value' where session_id='$key' ";
$qid = mysql_query($qry, $SESS_DBH);
}
return $qid;
}
function sess_destroy($key) {
global $SESS_DBH;
$qry = "delete from sessions where session_id = '$key'";
$qid = mysql_query($qry, $SESS_DBH);
return $qid;
}
function sess_gc($maxlifetime) {
global $SESS_DBH;
$old = time() - $maxlifetime;
$old = mysql_real_escape_string($old);
$qry = "delete from sessions where session_last_access < " . $old;
$qid = mysql_query($qry, $SESS_DBH);
return mysql_affected_rows($SESS_DBH);
}
session_module_name();
session_set_save_handler("sess_open", "sess_close", "sess_read", "sess_write", "sess_destroy", "sess_gc");
session_start();