Method file
Session implementation file: memcachedsession.php
Implementation principle (also is the implementation principle of PHP internal session):
1. First judge whether the client has SessionID,
A. Not to add a SessionID to the client, usually a 32-bit hash code, while initializing an array to do the session container
B. If the client has SessionID, then use this sessionid to memcached to check the data.
2. Users can modify the session value in the session container during the page execution
3. The end of the page will be the user's session container as a value, to the user's SessionID as a key, the key value to save to
Memcached inside
Copy Code code as follows:
<?php
memcached Server Connection Address
$_memcacheauth = Array (
' Host ' => ' localhost '
, ' Port ' => 11211
);
/*
Get some initialization setting values
*/
$_session_name = Ini_get ("Session.name"); Name of SessionID
$_session_time = Ini_get ("Session.cookie_lifetime"); SessionID The maximum save time for this cookie
$_session_expire = Ini_get ("Session.gc_maxlifetime"); The expiration time of the session key value pair inside the memcached
$_session_memkey = ""; SessionID value
/*
A custom _session_start () method that replaces the native Session_Start () method of PHP
The logic should be more clear.
*/
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 ();
}
}
Register a handler, which will be executed at the end of the page execution
Register_shutdown_function ("_session_save_handler");
}
/*
The last method that the page executes to save the session value, and to turn off the memcached connection
*/
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);
}
?>
Test files:
Set Session value
Copy Code code as follows:
<?php
/*
Set session value file: session_set.php
*/
Include_once "memcachedsession.php";
_session_start ();
$_session[' a '] = time ();
?>
Get Session Value
Copy Code code as follows:
<?php
/*
Get session Value File: session_get.php
*/
Include_once "memcachedsession.php";
_session_start ();
function GetSession ()
{
Echo $_session[' a '];
}
GetSession ();
?>
Memcached buffer application is still very good drip, oh,,,
Reprint: Jincon ' s Package blog http://www.yi1.com.cn