Home > Backend Development > PHP Tutorial > PHP uses memcache to realize multi-server shared session

PHP uses memcache to realize multi-server shared session

WBOY
Release: 2016-07-25 08:56:06
Original
1127 people have browsed it
  1. [Session]
  2. ; Handler used to store/retrieve data.
  3. session.save_handler = files; This is the session method, the default files is enough, which means file storage.
Copy the code

There are two other ways, user and memcache. The user mode refers to the handle of the session defined by oneself (that is, the user), which is used for session access, etc. This can store the session extension in the database. In memcache mode, you need to configure memcache and session.save_path.

Use memcache for PHP’s session.save_handler:

  1. ini_set("session.save_handler", "memcache");
  2. ini_set("session.save_path", "tcp://127.0.0.1:11211,tcp://192.168.1.12:11211") ;
Copy code

Use memcached for PHP's session.save_handler:

  1. ini_set("session.save_handler","memcached");
  2. ini_set("session.save_path","127.0.0.1:11211");
Copy code

The following introduces how PHP implements memcache sharing for multi-server session sharing. example: Customize session processing mechanism.

  1. /* vim: set expandtab tabstop=4 shiftwidth=4 foldmethod=marker: */
  2. //==================== ========================
  3. // Program: Memcache-Based Session Class
  4. // Function: Session function class based on Memcache storage
  5. //= ==========================================
  6. /**
  7. * File: MemcacheSession.inc.php
  8. * Class name: MemcacheSession Class
  9. * Function: Independently implement the Session function based on Memcache storage
  10. * Description: This class is to implement the Session function, basically through
  11. * Set the client's Cookie To save the SessionID,
  12. * then save the user's data on the server side, and finally determine whether a data belongs to the user through
  13. * the Session Id in the cookie,
  14. * and then perform corresponding data operations
  15. *
  16. * This method is suitable for Memcache The way to store session data in memory,
  17. * At the same time, if you build a distributed Memcache server,
  18. * can save a lot of cached data, and is suitable for situations where there are a lot of users and large concurrency
  19. *
  20. * Note: This class must require PHP The Memcache extension is installed or the PHP API of Memcache is required
  21. * To obtain the Memcache extension, please visit: http://pecl.php.net
  22. */
  23. //Set the SESSION validity time in seconds
  24. define('SESS_LIFTTIME', 3600);
  25. //Define memcache configuration information
  26. define('MEMCACHE_HOST', 'localhost');
  27. define('MEMCACHE_PORT' ', '10000');
  28. if (!defined('MemcacheSession'))
  29. {
  30. define('MemcacheSession', TRUE);
  31. class MemacheSession
  32. {
  33. // {{{ Class member attribute definition
  34. static $mSessSavePath ;
  35. static $mSessName;
  36. static $mMemcacheObj;
  37. // }}}
  38. // {{{ Initialization constructor
  39. /**
  40. * Constructor
  41. *
  42. * @param string $login_user Login user
  43. * @param int $login_type User type
  44. * @param string $login_sess Login Session value
  45. * @return Esession
  46. */
  47. public function __construct()
  48. {
  49. //My memcache It is compiled as a php module and can be called directly
  50. //If not, please include the Memcache-client.php file yourself
  51. if (!class_exists('Memcache') || !function_exists('memcache_connect'))
  52. {
  53. die('Fatal Error:Can not load Memcache extension!');
  54. }
  55. if (!empty(self::$mMemcacheObj) && is_object(self::$mMemcacheObj))
  56. {
  57. return false;
  58. }
  59. self::$mMemcacheObj = new Memcache;
  60. if (!self::$mMemcacheObj->connect(MEMCACHE_HOST , MEMCACHE_PORT))
  61. {
  62. die('Fatal Error: Can not connect to memcache host '. MEMCACHE_HOST . ':'. MEMCACHE_PORT);
  63. }
  64. return TRUE;
  65. }
  66. // }}}
  67. /**{{{ sessOpen($pSavePath, $name)
  68. *
  69. * @param String $pSavePath
  70. * @param String $pSessName
  71. *
  72. * @return Bool TRUE/FALSE
  73. */
  74. public function sessOpen($pSavePath = '', $pSessName = '')
  75. {
  76. self::$mSessSavePath = $pSavePath;
  77. self::$mSessName = $pSessName;
  78. return TRUE;
  79. }
  80. // }}}
  81. /**{{{ sessClose()
  82. *
  83. * @param NULL
  84. *
  85. * @return Bool TRUE/FALSE
  86. */
  87. public function sessClose()
  88. {
  89. return TRUE;
  90. }
  91. // }}}
  92. /**{{{ sessRead($wSessId)
  93. *
  94. * @param String $wSessId
  95. *
  96. * @return Bool TRUE/FALSE
  97. */
  98. public function sessRead($wSessId = '')
  99. {
  100. $wData = self::$mMemcacheObj->get( $wSessId);
  101. //Read the data first, if not, initialize one
  102. if (!empty($wData))
  103. {
  104. return $wData;
  105. }
  106. else
  107. {
  108. //Initialize an empty record
  109. $ ret = self::$mMemcacheObj->set($wSessId, '', 0, SESS_LIFTTIME);
  110. if (TRUE != $ret)
  111. {
  112. die("Fatal Error: Session ID $wSessId init failed!") ;
  113. return FALSE;
  114. }
  115. return TRUE;
  116. }
  117. }
  118. // }}}
  119. /**{{{ sessWrite($wSessId, $wData)
  120. *
  121. * @param String $wSessId
  122. * @param String $wData
  123. *
  124. * @return Bool TRUE/FALSE
  125. */
  126. public function sessWrite($wSessId = '', $wData = '')
  127. {
  128. $ret = self::$mMemcacheObj->replace($wSessId, $wData, 0 , SESS_LIFTTIME);
  129. if (TRUE != $ret)
  130. {
  131. die("Fatal Error: SessionID $wSessId Save data failed!");
  132. return FALSE;
  133. }
  134. return TRUE;
  135. }
  136. // }}}
  137. /**{{{ sessDestroy($wSessId)
  138. *
  139. * @param String $wSessId
  140. *
  141. * @return Bool TRUE/FALSE
  142. */
  143. public function sessDestroy($wSessId = '')
  144. {
  145. self::sessWrite($wSessId);
  146. return FALSE;
  147. }
  148. // }}}
  149. /** {{{ sessGc()
  150. *
  151. * @param NULL
  152. *
  153. * @return Bool TRUE/FALSE
  154. */
  155. public function sessGc()
  156. {
  157. //No additional recycling required, memcache has its own expired recycling mechanism
  158. return TRUE;
  159. }
  160. // }}}
  161. /**{{{ initSess()
  162. *
  163. * @param NULL
  164. *
  165. * @return Bool TRUE/FALSE
  166. */
  167. public function initSess()
  168. {
  169. //Do not use GET/POST variable method
  170. ini_set('session.use_trans_sid', 0);
  171. //Set the maximum lifetime of garbage collection
  172. ini_set('session.gc_maxlifetime', SESS_LIFTTIME) ;
  173. //How to use COOKIE to save SESSION ID
  174. ini_set('session.use_cookies', 1);
  175. ini_set('session.cookie_path', '/');
  176. $domain = '.imysql.cn';
  177. //Multiple hosts share the COOKIE that saves the SESSION ID
  178. ini_set('session.cookie_domain', $domain);
  179. //Set session.save_handler to user instead of the default files
  180. session_module_name('user');
  181. //Define the method names corresponding to various SESSION operations:
  182. session_set_save_handler(
  183. array('MemacheSession', 'sessOpen'), //corresponds to the static method My_Sess::open(), the same below.
  184. array('MemacheSession', 'sessClose'),
  185. array('MemacheSession', 'sessRead'),
  186. array('MemacheSession', 'sessWrite'),
  187. array('MemacheSession', 'sessDestroy'),
  188. array ('MemacheSession', 'sessGc')
  189. );
  190. session_start();
  191. return TRUE;
  192. }
  193. // }}}
  194. }//end class
  195. }//end define
  196. $memSess = new MemacheSession;
  197. $memSess->initSess();
  198. ?>
Copy the code

Include MemacheSession.inc.php directly in the header file in the program to use this class.

Test example. 1. Create a session

  1. //set_session.php
  2. session_start();
  3. if (!isset($_SESSION['admin'])) {
  4. $_SESSION['TEST'] = 'wan';
  5. }
  6. print $_SESSION['admin'];
  7. print "/n";
  8. print session_id();
  9. ?>
Copy code

2, use sessionid to query in memcached:

  1. //get_session.php
  2. $mem = new Memcache;
  3. $mem->connect("127.0.0.1", 11211);
  4. var_dump($mem->get( '0935216dbc0d721d629f89efb89affa6'));
  5. ?>
Copy code

Note: memcache PECL In future versions, you can directly set php.ini to set session.save_handler.

For example:

session.save_handler = memcache session.save_path = "tcp://host:port?persistent=1&weight=2&timeout=2&retry_interval=15,tcp://host2:port2"


source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template