1.创建存储数据的mysql表
DROP TABLE IF EXISTS `session`.`sessioninfo`;
CREATE TABLE `session`.`sessioninfo` (
`SID` char(32) NOT NULL,
`expiration` int(10) unsigned NOT NULL,
`value` text NOT NULL,
PRIMARY KEY (`SID`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
2.创建6个定制处理器函数,并用session_set_save_handler注册
mysqlsessionhandlers.php
<?php
/*
* mysql_session_open()
* opens a persistent server connectiona and selects the database.
*/
function mysql_session_open($session_path,$session_name){
mysql_connect("localhost","root","root") or die("Can't connect to MySQL server!");
mysql_select_db("session") or die("Can't select MySQL session database");
}
/*
* mysql_session_close()
* Doesn't actually do anything since the server connection is
* persitne.Keep in mind that although this function
* doesn't do anything in my particular implomentation,it
* must nonetheless be defined
*/
function mysql_session_close(){
return 1;
}
/*
* mysql_session_select()
* Reads the session data from the database
*/
function mysql_session_select($SID){
$query="select value from sessionfinfo where SID='$SID' and expiration >".time();
$result=mysql_query($query);
if(mysql_num_rows($result)){
$row=mysql_fetch_assoc($result);
$value=$row['value'];
return $value;
}else{
return "";
}
}
/*
* mysql_session_write()
* This function writes the session data to the database.
* If that SID already exists,then the existing data will be updated.
*/
function mysql_session_write($SID,$value){
$lifetime=get_cfg_var("session.gc_maxlifetime");
$expiration=time()+$lifetime;
$query="insert into sessioninfo values('$SID','$expiration','$value')";
$result=mysql_query($query);
if(!$result){
$query="update sessioninfo set expiration='$expiration' value='$value' where SID='$SID' and expiration>".time();
$result=mysql_query($query);
}
}
/*
* mysql_session_destory()
* Deletes all session information having input SID(only on row)
*/
function mysql_session_destroy($SID){
$query="delete from sessioninfo where SID='$SID";
$result=mysql_query($query);
}
function mysql_session_garbage_collect($lifetime){
$query="delete from sessioninfo where expiration<".time()-$lifetime;
$result=mysql_query($query);
return mysql_affected_rows($result);
}
session_set_save_handler("mysql_session_open","mysql_session_close","mysql_session_select","mysql_session_write","mysql_session_destroy","mysql_session_garbage_collect");
?>
3.测试
<?php
include "mysqlsessionhandlers.php";
session_start();
$_SESSION["name"]="jickcai";
?>
会看到数据已插入到数据库里.