PHP uses Memcache to implement multi-server sharing session

Source: Internet
Author: User
Tags php session
    1. [Session]
    2. ; Handler used to store/retrieve data.
    3. Session.save_handler = files; This is the way of the session, the default files can be used to indicate the storage.
Copy Code

There are two different ways to do this, user and memcache. User mode refers to the handle of the session defined by itself (that is, the user), for the session access, etc., which can be extended to the database in the session. Memcache mode, you need to configure the Memcache, but also configure the Session.save_path.

Use Memcache to make PHP 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 to make PHP 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 introduction, PHP implementation of multi-server session sharing Memcache sharing method. Example: Customizing the 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: Autonomous implementation of the Session function based on memcache storage
  10. * Description: This class is to implement the function of the session, basically through
  11. * Set the client's cookie to save the SessionID,
  12. * Then save the user's data on the server side, finally through the
  13. * The session ID in the cookie to determine if a data is a user,
  14. * then perform the corresponding data operation
  15. *
  16. * This method is suitable for storing session data in Memcache memory mode,
  17. * At the same time if you build a distributed Memcache server,
  18. * Able to save quite a bit of cache data, and suitable for a larger number of concurrent users.
  19. *
  20. * Note: This class must require PHP to install the memcache extension or must have memcache PHP API
  21. * Get memcache Extension visit: http://pecl.php.net
  22. */
  23. Set the SESSION effective time, in seconds
  24. Define (' Sess_lifttime ', 3600);
  25. Defining 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 Property definition
  34. Static $mSessSavePath;
  35. Static $mSessName;
  36. Static $MMEMCACHEOBJ;
  37. // }}}
  38. {{{} Initialize constructor
  39. /**
  40. * Constructor function
  41. *
  42. * @param string $login _user logged in 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 is compiled in the form of 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, and if not, initialize a
  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 need for additional recycling, Memcache has its own outdated 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 mode
  170. Ini_set (' Session.use_trans_sid ', 0);
  171. Set the maximum time to live for garbage collection
  172. Ini_set (' Session.gc_maxlifetime ', sess_lifttime);
  173. How to save SESSION ID using a COOKIE
  174. Ini_set (' session.use_cookies ', 1);
  175. Ini_set (' Session.cookie_path ', '/');
  176. $domain = '. imysql.cn ';
  177. Multi-host sharing COOKIE that holds 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 name that corresponds to each operation of the SESSION:
  182. Session_set_save_handler (
  183. Array (' memachesession ', ' sessopen '),//corresponds to static method My_sess::open (), same as 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 Code

You can use this class by including MemacheSession.inc.php directly in the header file in your program.

The test instance. 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 memcached query:

    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: In future versions of Memcache PECL, you can set the php.ini settings Session.save_handler directly.

Like what:

Session.save_handler = memcache Session.save_path = "tcp://host:port?persistent=1&weight=2&timeout=2& Retry_interval=15,tcp://host2:port2 "
  • Related Article

    Contact Us

    The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

    If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

    A Free Trial That Lets You Build Big!

    Start building with 50+ products and up to 12 months usage for Elastic Compute Service

    • Sales Support

      1 on 1 presale consultation

    • After-Sales Support

      24/7 Technical Support 6 Free Tickets per Quarter Faster Response

    • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.