时间:2021-07-01 10:21:17 帮助过:26人阅读
//memcached服务器连接地址
$_MEMCACHEAUTH = array(
'host' => 'localhost'
, 'port' => 11211
);
/*
获取一些初始化设置值
*/
$_SESSION_NAME = ini_get("session.name"); //sessionid的名称
$_SESSION_TIME = ini_get("session.cookie_lifetime"); //sessionid这个cookie的最大保存时间
$_SESSION_EXPIRE = ini_get("session.gc_maxlifetime"); //session键值对在memcached里面的过期时间
$_SESSION_MEMKEY = ""; //sessionid值
/*
自定义的_session_start()方法,替换PHP的原生session_start()方法
逻辑应该是比较清楚的
*/
function _session_start()
{
global $_SESSION_NAME, $_SESSION_TIME, $_SESSION_MEMKEY;
global $_SESSION;
global $_MEMCACHEAUTH, $_sessionmem;
$_sessionmem = memcache_connect($_MEMCACHEAUTH['host'], $_MEMCACHEAUTH['port']);
if ( empty($_COOKIE[$_SESSION_NAME]) )
{
$_SESSION_MEMKEY = md5( uniqid() );
setcookie($_SESSION_NAME, $_SESSION_MEMKEY , $_SESSION_TIME, "/");
$_SESSION = array();
}
else
{
$_SESSION_MEMKEY = $_COOKIE[$_SESSION_NAME];
$_SESSION = memcache_get($_sessionmem, $_SESSION_MEMKEY );
if ( $_SESSION === FALSE )
{
$_SESSION = array();
}
}
//注册一个handler,这个函数会在页面执行完的时候执行
register_shutdown_function("_session_save_handler");
}
/*
页面最后执行的方法,用于保存session值,以及关闭memcached连接
*/
function _session_save_handler()
{
global $_sessionmem;
global $_SESSION, $_SESSION_NAME, $_SESSION_EXPIRE, $_SESSION_MEMKEY;
memcache_set($_sessionmem, $_SESSION_MEMKEY, $_SESSION, 0, $_SESSION_EXPIRE);
memcache_close($_sessionmem);
}
?>
测试文件:
设置session值
代码如下:
/*
设置session值文件:session_set.php
*/
include_once "memcachedsession.php";
_session_start();
$_SESSION['a'] = time();
?>
获取session值
代码如下:
/*
获取session值文件:session_get.php
*/
include_once "memcachedsession.php";
_session_start();
function getsession()
{
echo $_SESSION['a'];
}
getsession();
?>
Memcached的缓冲应用还是非常不错滴,呵呵,,,
转载:jincon's 包 blog http://www.yi1.com.cn