Using Memcached to implement the session mechanism in PHP to replace PHP's native session support

  • 2020-03-31 21:06:50
  • OfStack

Methods the file
Session implementation file :memcachedsession.php
Implementation principle (also the implementation principle of PHP internal session) :
1. First, determine whether the client has a sessionid.
A. Without adding a sessionid to the client, usually a 32-bit hash code, and initializing an array as the session container
B. If the client has a sessionid, use this sessionid to look up the data in memcached.
2. The user can modify the session value in the session container during the page execution
3. At the end of the page, the user's session container will be used as the value, and the user's sessionid will be used as the key to save this key-value pair to
Memcached inside
 
<?php 
//The memcached server connection address
$_MEMCACHEAUTH = array( 
'host' => 'localhost' 
, 'port' => 11211 
); 
 
$_SESSION_NAME = ini_get("session.name"); //The name of the sessionid
$_SESSION_TIME = ini_get("session.cookie_lifetime"); //The maximum save time of sessionid cookie
$_SESSION_EXPIRE = ini_get("session.gc_maxlifetime"); //The expiration time of the session key-value pair in memcached
$_SESSION_MEMKEY = ""; //Sessionid value
 
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 is executed when the page is finished
register_shutdown_function("_session_save_handler"); 
} 
 
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 file:
Setting the session value
 
<?php 
 
include_once "memcachedsession.php"; 
_session_start(); 
$_SESSION['a'] = time(); 
?> 

Access to the session value
 
<?php 
 
include_once "memcachedsession.php"; 
_session_start(); 
function getsession() 
{ 
echo $_SESSION['a']; 
} 
getsession(); 
?> 

The application of Memcached is still very good.
Jincon's package blog http://www.yi1.com.cn

Related articles: