search
HomeBackend DevelopmentPHP TutorialPHP uses memcache to realize multi-server shared session

  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"


Statement
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
How do you set the session cookie parameters in PHP?How do you set the session cookie parameters in PHP?Apr 22, 2025 pm 05:33 PM

Setting session cookie parameters in PHP can be achieved through the session_set_cookie_params() function. 1) Use this function to set parameters, such as expiration time, path, domain name, security flag, etc.; 2) Call session_start() to make the parameters take effect; 3) Dynamically adjust parameters according to needs, such as user login status; 4) Pay attention to setting secure and httponly flags to improve security.

What is the main purpose of using sessions in PHP?What is the main purpose of using sessions in PHP?Apr 22, 2025 pm 05:25 PM

The main purpose of using sessions in PHP is to maintain the status of the user between different pages. 1) The session is started through the session_start() function, creating a unique session ID and storing it in the user cookie. 2) Session data is saved on the server, allowing data to be passed between different requests, such as login status and shopping cart content.

How can you share sessions across subdomains?How can you share sessions across subdomains?Apr 22, 2025 pm 05:21 PM

How to share a session between subdomains? Implemented by setting session cookies for common domain names. 1. Set the domain of the session cookie to .example.com on the server side. 2. Choose the appropriate session storage method, such as memory, database or distributed cache. 3. Pass the session ID through cookies, and the server retrieves and updates the session data based on the ID.

How does using HTTPS affect session security?How does using HTTPS affect session security?Apr 22, 2025 pm 05:13 PM

HTTPS significantly improves the security of sessions by encrypting data transmission, preventing man-in-the-middle attacks and providing authentication. 1) Encrypted data transmission: HTTPS uses SSL/TLS protocol to encrypt data to ensure that the data is not stolen or tampered during transmission. 2) Prevent man-in-the-middle attacks: Through the SSL/TLS handshake process, the client verifies the server certificate to ensure the connection legitimacy. 3) Provide authentication: HTTPS ensures that the connection is a legitimate server and protects data integrity and confidentiality.

The Continued Use of PHP: Reasons for Its EnduranceThe Continued Use of PHP: Reasons for Its EnduranceApr 19, 2025 am 12:23 AM

What’s still popular is the ease of use, flexibility and a strong ecosystem. 1) Ease of use and simple syntax make it the first choice for beginners. 2) Closely integrated with web development, excellent interaction with HTTP requests and database. 3) The huge ecosystem provides a wealth of tools and libraries. 4) Active community and open source nature adapts them to new needs and technology trends.

PHP and Python: Exploring Their Similarities and DifferencesPHP and Python: Exploring Their Similarities and DifferencesApr 19, 2025 am 12:21 AM

PHP and Python are both high-level programming languages ​​that are widely used in web development, data processing and automation tasks. 1.PHP is often used to build dynamic websites and content management systems, while Python is often used to build web frameworks and data science. 2.PHP uses echo to output content, Python uses print. 3. Both support object-oriented programming, but the syntax and keywords are different. 4. PHP supports weak type conversion, while Python is more stringent. 5. PHP performance optimization includes using OPcache and asynchronous programming, while Python uses cProfile and asynchronous programming.

PHP and Python: Different Paradigms ExplainedPHP and Python: Different Paradigms ExplainedApr 18, 2025 am 12:26 AM

PHP is mainly procedural programming, but also supports object-oriented programming (OOP); Python supports a variety of paradigms, including OOP, functional and procedural programming. PHP is suitable for web development, and Python is suitable for a variety of applications such as data analysis and machine learning.

PHP and Python: A Deep Dive into Their HistoryPHP and Python: A Deep Dive into Their HistoryApr 18, 2025 am 12:25 AM

PHP originated in 1994 and was developed by RasmusLerdorf. It was originally used to track website visitors and gradually evolved into a server-side scripting language and was widely used in web development. Python was developed by Guidovan Rossum in the late 1980s and was first released in 1991. It emphasizes code readability and simplicity, and is suitable for scientific computing, data analysis and other fields.

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Atom editor mac version download

Atom editor mac version download

The most popular open source editor

SublimeText3 English version

SublimeText3 English version

Recommended: Win version, supports code prompts!

mPDF

mPDF

mPDF is a PHP library that can generate PDF files from UTF-8 encoded HTML. The original author, Ian Back, wrote mPDF to output PDF files "on the fly" from his website and handle different languages. It is slower than original scripts like HTML2FPDF and produces larger files when using Unicode fonts, but supports CSS styles etc. and has a lot of enhancements. Supports almost all languages, including RTL (Arabic and Hebrew) and CJK (Chinese, Japanese and Korean). Supports nested block-level elements (such as P, DIV),

DVWA

DVWA

Damn Vulnerable Web App (DVWA) is a PHP/MySQL web application that is very vulnerable. Its main goals are to be an aid for security professionals to test their skills and tools in a legal environment, to help web developers better understand the process of securing web applications, and to help teachers/students teach/learn in a classroom environment Web application security. The goal of DVWA is to practice some of the most common web vulnerabilities through a simple and straightforward interface, with varying degrees of difficulty. Please note that this software

MinGW - Minimalist GNU for Windows

MinGW - Minimalist GNU for Windows

This project is in the process of being migrated to osdn.net/projects/mingw, you can continue to follow us there. MinGW: A native Windows port of the GNU Compiler Collection (GCC), freely distributable import libraries and header files for building native Windows applications; includes extensions to the MSVC runtime to support C99 functionality. All MinGW software can run on 64-bit Windows platforms.