首先要进行的配置如下:
1.php.ini中将session.save_handler = files 中的files改为User,其他默认即可,重启Apache
2.本实例创建的数据库名叫php, username: root password:root
本实例设计的数据库的表结构如下所示,代码如下:
create table mysession(
session_key char(32) not null,
session_data text,
session_expiry int(11),
primary key(session_key)
);
第一列表示存储session ID,第二列存储session中的数据,第三列存储有效期,下面就是关键的那份自定义函数的实现session_set_save_handler(......),代码如下:
user-define-session-inc.php
<?php
function mysession_open($save_path, $session_name)
{
@mysql_connect("localhost", "root", "root") or die("数据库服务器连接失败");
@mysql_select_db("php") or die("数据库不存在或不可用");
return true;
}
function mysession_close()
{
return true;
}
function mysession_read($key)
{
@mysql_connect("localhost", "root", "root") or die("数据库服务器连接失败");
@mysql_select_db("php") or die("数据库不存在或不可用");
$expiry_time = time();
$query = @mysql_query("select session_data from mysession where session_key = '$key' and session_expiry > $expiry_time") or die("SQL语句执行失败");
if($row = mysql_fetch_array($query))
return $row['session_data'];
else
return false;
}
function mysession_write($key, $data)
{
@mysql_connect("localhost", "root", "root") or die("数据库服务器连接失败");
@mysql_select_db("php") or die("数据库不存在或不可用");
$expiry_time = time() + 1200;
$query = @mysql_query("select session_data from mysession where session_key = '$key'") or die("SQL语句执行失败");
if(mysql_numrows($query) == 0)
{
$query = @mysql_query("insert into mysession values('$key', '$data', $expiry_time)") or die("SQL语句执行失败");
}
else
{
$query = @mysql_query("update mysession set session_data = '$data', session_expiry = $expiry_time where session_key = '$key'") or die("SQL语句执行失败");
}
return $query;
}
function mysession_destroy($key)
{
@mysql_connect("localhost", "root", "root") or die("数据库服务器连接失败");
@mysql_select_db("php") or die("数据库不存在或不可用");
$query = @mysql_query("delete from mysession where session_key = '$key'")
or die("SQL语句执行失败");
return $query;
}
function mysession_gc($expiry_time)
{
@mysql_connect("localhost", "root", "root") or die("数据库服务器连接失败");
@mysql_select_db("php") or die("数据库不存在或不可用");
$expiry_time = time();
$query = @mysql_query("delete from mysession where session_expiry < $expiry_time") or die("SQL语句执行失败");
return $query;
}
session_set_save_handler('mysession_open','mysession_close','mysession_read','mysession_write','mysession_destroy','mysession_gc');
?>
最后面就是测试代码:
1.存储页面 save.php
<?php
include('user-define-session-inc.php');
session_start();
$_SESSION['username'] = "Simon";
$_SESSION['password'] = "123456";
?>
2.显示页面 show.php
<?php
include('user-define-session-inc.php');
session_start();
echo "UserName:".$_SESSION['username']."
";
echo "PassWord:".$_SESSION['password']."
";
?>
--转自