Home Backend Development PHP Tutorial PHP shares SESSION operations on different servers_PHP tutorial

PHP shares SESSION operations on different servers_PHP tutorial

Jul 13, 2016 pm 05:52 PM
php session one superior different shared exist operate server of website origin question

1. Origin of the problem 7 O8 X8 R7 o& Z) Y# i3 O
Slightly larger websites usually have several servers. Each server runs modules with different functions and uses different second-level domain names. For a comprehensive website, the user system is unified, that is, a set of user names, The password can be used to log in to all modules of the entire website. Sharing user data between servers is relatively easy to implement. You only need to put a database server on the back end, and each server can access user data through a unified interface. But there is still a problem, that is, after the user logs in to this server, when entering other modules of another server, he still needs to log in again. This is a one-time login, and all common problems are mapped to technology. In fact, it is between various servers. How to share SESSION data. ! n) o+ ~2 R# T8 P$ @ R% P C
/ S" G* k: }5 j' R( {7 v5 {

2. How PHP SESSION works # Q; Z3 ?; F2 N0 b2 w
. C) Z, n# ]9 ^- K9 B8 }- H; G
Before solving the problem, let's first understand how PHP SESSION works. When the client (such as a browser) logs in to the website, the visited PHP page can use session_start() to open SESSION, which will generate the client's unique identification SESSION ID (this ID can be obtained/set through the function session_id()). The SESSION ID can be retained on the client in two ways, so that the PHP program can learn the client's SESSION ID when requesting different pages; one is to automatically add the SESSION ID to the GET URL, or the POST form, by default. Under the first method, the variable name is PHPSESSID; the other method is to save the SESSION ID in the COOKIE through COOKIE. By default, the name of this COOKIE is PHPSESSID. Here we mainly use the COOKIE method for explanation, because it is widely used.

So where is the SESSION data stored? On the server side of course, but not in memory, but in a file or database. By default, the SESSION saving method set in php.ini is files (session.save_handler = files), that is, the SESSION data is saved by reading and writing files, and the directory where the SESSION file is saved is specified by session.save_path, and the file name starts with sess_ is the prefix, followed by SESSION ID, such as: sess_c72665af28a8b14c0fe11afe3b59b51b. The data in the file is the SESSION data after serialization. If the number of visits is large, there may be more SESSION files generated. In this case, you can set up a hierarchical directory to save SESSION files, which will improve the efficiency a lot. The setting method is: session.save_path="N;/save_path", N is hierarchical. level, save_path is the starting directory. When writing SESSION data, PHP will obtain the client's SESSION_ID, and then use this SESSION ID to find the corresponding SESSION file in the specified SESSION file storage directory. If it does not exist, create it, and finally serialize the data and write it to the file. . Reading SESSION data is a similar operation process. The read data needs to be deserialized and the corresponding SESSION variable is generated. & S! m7 D7 J% O
; [' U9 u2 t- d

3. Main obstacles and solutions to multi-server sharing SESSION

By understanding the working principle of SESSION, we can find that by default, each server will generate a SESSION ID for the same client respectively. For example, for the same user browser, the SESSION ID generated by server A is 30de1e9de3192ba6ce2992d27a1b6a0a, The B server generates c72665af28a8b14c0fe11afe3b59b51b. In addition, PHP's SESSION data are stored separately in the file system of this server. As shown in the figure below: 8 w) T" B/ f, J+ t$ }1 R: f; q
) O# ^1 |, C- u+ t# K; Z
Once you’ve identified the problem, you can start solving it. If you want to share SESSION data, you must achieve two goals: One is that the SESSION ID generated by each server for the same client must be the same and can be passed through the same COOKIE, which means that each server must be able to read the same SESSION ID. COOKIE named PHPSESSID; the other is that the storage method/location of SESSION data must ensure that each server can access it. Simply put, multiple servers share the client's SESSION ID and must also share the server's SESSION data.
" X8 {7 ]% Q5 k# a1 L
The realization of the first goal is actually very simple. You only need to specially set the domain of the COOKIE. By default, the domain of the COOKIE is the domain name/IP address of the current server. If the domain is different, the domain of each server will be different. The set COOKIE cannot be accessed by each other. For example, the server of www.aaa.com cannot read and write the COOKIE set by the server of www.bbb.com.
- g8 q8 |; U1 u8 `6 K* J
The servers of the same website we are talking about here have their own particularity, that is, they belong to the same first-level domain. For example: aaa.infor96.com and www.infor96.com both belong to the domain .infor96.com, then we can Set the domain of the COOKIE to .infor96.com, so that aaa.infor96.com, www.infor96.com, etc. can access this COOKIE. The setting method in PHP code is as follows:

        ini_set('session.cookie_domain', '.infor96.com');
?>

Copy code
In this way, the purpose of each server sharing the same client SESSION ID is achieved. ; l, @8 W1 ]& ~. S: y9 O; {( @" k

The second goal can be achieved using file sharing methods, such as NFS, but the setup and operation are somewhat complicated. We can refer to the previously mentioned method of unifying the user system, that is, using a database to save SESSION data, so that each server can easily access the same data source and obtain the same SESSION data.

The solution is as shown below: : o T/ N( c0 x P/ ^" U6 A& c

5 H+ K1 h, f; `2 o) U

4. Code implementation ! m1 C8 / r1 v) O
0 V3 {( ^; |! o! $ C) u3 Y0 b
First create a data table. The SQL statement of My SQL is as follows:

CREATE TABLE `sess` (
​​​​​ `sesskey` varchar(32) NOT NULL default '',
             `expiry` bigint(20) NOT NULL default '0',
            `data` longtext NOT NULL,
PRIMARY KEY (`sesskey`),
KEY `expiry` (`expiry`)
) TYPE=MyISAMsesskey is the SESSION ID, expiry is the SESSION expiration time, and data is used to save SESSION data.

Copy code
By default, SESSION data is saved in file mode. If you want to save it in database mode, you must redefine the processing functions of each SESSION operation. PHP provides the session_set_save_handle() function. You can use this function to customize the SESSION processing process. Of course, you must first change session.save_handler to user, which can be set in PHP:

Session_module_name('user');
?>

Copy code
Next, let’s focus on the session_set_save_handle() function. This function has six parameters:

session_set_save_handler (string open, string close, string read, string write, string destroy, string gc) Each parameter is the function name of each operation. These operations are: open, close, read, write, destroy, Garbage collection. There are detailed examples in the PHP manual. Here we use OO to implement these operations. The detailed code is as follows:

Define('MY_SESS_TIME', 3600); //SESSION survival time
//Class definition
Class My_Sess
{
         function init()
           {
                $domain = '.infor96.com';
//Do not use GET/POST variable method
ini_set('session.use_trans_sid', 0);
//Set the maximum garbage collection lifetime
           ini_set('session.gc_maxlifetime', MY_SESS_TIME);
 
//How to use COOKIE to save SESSION ID
ini_set('session.use_cookies', 1);
ini_set('session.cookie_path', '/');
//Multiple hosts share the COOKIE that saves the SESSION ID
             ini_set('session.cookie_domain',     $domain);
 
​​​​​​ //Set session.save_handler to user instead of the default files
session_module_name('user');
//Define the method names corresponding to each operation of SESSION:
session_set_save_handler(
                  array ('My_Sess', 'open'), // Corresponds to the static method My_Sess::open(), the same below.
array('My_Sess', 'close'),
array('My_Sess', 'read'),
array('My_Sess', 'write'),
array('My_Sess', 'destroy'),
                 array('My_Sess', 'gc')
);
                                    //end function
 
         function open($save_path, $session_name) {
             return true;
                                    //end function
 
         function close() {
global $MY_SESS_CONN;
 
                                                                                                                                                            if ($MY_SESS_CONN) {     $MY_SESS_CONN->Close();
            }
             return true;
                              //end function
 
         function read($sesskey) {
global $MY_SESS_CONN;
 
$sql = 'SELECT data FROM sess WHERE sesskey=' . $MY_SESS_CONN->qstr($sesskey) . ' AND expiry>=' . time();
$rs =& ​​$MY_SESS_CONN->Execute($sql);
                  if ($rs) {
If ($rs->EOF) {
                          return '';
} Else {// Read the session data corresponding to the session id
$v = $rs->fields[0];
$rs->Close();
                       return $v;
                                     //end if
                                //end if
              return '';
                                    //end function
 
         function write($sesskey, $data) {
global $MY_SESS_CONN;
                                                                                          $qkey = $MY_SESS_CONN->qstr($sesskey);
                $expiry = time() + My_SESS_TIME;                                                                          //Write SESSION
                $arr = array(
‘sesskey’ => $qkey,
'expiry' => $expiry,
                                                                                                                                                                                                                                                                    isn t- having having to have to do so to                  $MY_SESS_CONN->Replace('sess', $arr, 'sesskey', $autoQuote = true);
             return true;
                              //end function
 
         function destroy($sesskey) {
global $MY_SESS_CONN;
 
$sql = 'DELETE FROM sess WHERE sesskey=' . $MY_SESS_CONN->qstr($sesskey);
$rs =& ​​$MY_SESS_CONN->Execute($sql);
             return true;
                              //end function
 
         function gc($maxlifetime = null) {
global $MY_SESS_CONN;
 
$sql = 'DELETE FROM sess WHERE expiry<' . time();
                 $MY_SESS_CONN->Execute($sql);
                                      // Due to frequent deletion operations on the table sess, it is easy to cause fragmentation,
​​​​​ //So the table is optimized during garbage collection.
               $sql = 'OPTIMIZE TABLE sess';
$MY_SESS_CONN->Execute($sql);
             return true;
                              //end function
}   ///:~
 
//Use ADOdb as the database abstraction layer.
​ require_once('adodb/adodb.inc.php');
//Database configuration items can be placed in the configuration file (such as: config.inc.php).
$db_type = 'mysql';
$db_host = '192.168.212.1';
$db_user = 'sess_user';
$db_pass = 'sess_pass';
$db_name = 'sess_db';
//Create a database connection, this is a global variable.
$GLOBALS['MY_SESS_CONN'] =& ADONewConnection($db_type);
$GLOBALS['MY_SESS_CONN']->Connect( $db_host, $db_user, $db_pass, $db_name);
//Initialize SESSION settings, must be run before session_start()! !
My_Sess::init(); www.2cto.com
?>

Copy code
5. Remaining issues ' % p* 9 a5 N+ G+ v

If the website has a large number of visits, SESSION's reading and writing will frequently operate on the database, so the efficiency will be significantly reduced. Considering that SESSION data is generally not very large, you can try to write a multi-threaded program in C/Java, use a HASH table to save the SESSION data, and read and write data through socket communication. In this way, the SESSION is saved in the memory, and the reading and writing speed is improved. It should be much faster. In addition, server load can be shared through load balancing.


Author: Ah He

www.bkjia.comtruehttp: //www.bkjia.com/PHPjc/478068.htmlTechArticle1. Origin of the problem 7 O8 X8 R7 o Z) Y# i3 O Slightly larger websites usually have Several servers, each running modules with different functions and using different second-level domain names...
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

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

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Hot Topics

Java Tutorial
1664
14
PHP Tutorial
1266
29
C# Tutorial
1239
24
Explain JSON Web Tokens (JWT) and their use case in PHP APIs. Explain JSON Web Tokens (JWT) and their use case in PHP APIs. Apr 05, 2025 am 12:04 AM

JWT is an open standard based on JSON, used to securely transmit information between parties, mainly for identity authentication and information exchange. 1. JWT consists of three parts: Header, Payload and Signature. 2. The working principle of JWT includes three steps: generating JWT, verifying JWT and parsing Payload. 3. When using JWT for authentication in PHP, JWT can be generated and verified, and user role and permission information can be included in advanced usage. 4. Common errors include signature verification failure, token expiration, and payload oversized. Debugging skills include using debugging tools and logging. 5. Performance optimization and best practices include using appropriate signature algorithms, setting validity periods reasonably,

Explain late static binding in PHP (static::). Explain late static binding in PHP (static::). Apr 03, 2025 am 12:04 AM

Static binding (static::) implements late static binding (LSB) in PHP, allowing calling classes to be referenced in static contexts rather than defining classes. 1) The parsing process is performed at runtime, 2) Look up the call class in the inheritance relationship, 3) It may bring performance overhead.

PHP Program to Count Vowels in a String PHP Program to Count Vowels in a String Feb 07, 2025 pm 12:12 PM

A string is a sequence of characters, including letters, numbers, and symbols. This tutorial will learn how to calculate the number of vowels in a given string in PHP using different methods. The vowels in English are a, e, i, o, u, and they can be uppercase or lowercase. What is a vowel? Vowels are alphabetic characters that represent a specific pronunciation. There are five vowels in English, including uppercase and lowercase: a, e, i, o, u Example 1 Input: String = "Tutorialspoint" Output: 6 explain The vowels in the string "Tutorialspoint" are u, o, i, a, o, i. There are 6 yuan in total

What are PHP magic methods (__construct, __destruct, __call, __get, __set, etc.) and provide use cases? What are PHP magic methods (__construct, __destruct, __call, __get, __set, etc.) and provide use cases? Apr 03, 2025 am 12:03 AM

What are the magic methods of PHP? PHP's magic methods include: 1.\_\_construct, used to initialize objects; 2.\_\_destruct, used to clean up resources; 3.\_\_call, handle non-existent method calls; 4.\_\_get, implement dynamic attribute access; 5.\_\_set, implement dynamic attribute settings. These methods are automatically called in certain situations, improving code flexibility and efficiency.

PHP and Python: Comparing Two Popular Programming Languages PHP and Python: Comparing Two Popular Programming Languages Apr 14, 2025 am 12:13 AM

PHP and Python each have their own advantages, and choose according to project requirements. 1.PHP is suitable for web development, especially for rapid development and maintenance of websites. 2. Python is suitable for data science, machine learning and artificial intelligence, with concise syntax and suitable for beginners.

PHP in Action: Real-World Examples and Applications PHP in Action: Real-World Examples and Applications Apr 14, 2025 am 12:19 AM

PHP is widely used in e-commerce, content management systems and API development. 1) E-commerce: used for shopping cart function and payment processing. 2) Content management system: used for dynamic content generation and user management. 3) API development: used for RESTful API development and API security. Through performance optimization and best practices, the efficiency and maintainability of PHP applications are improved.

PHP: A Key Language for Web Development PHP: A Key Language for Web Development Apr 13, 2025 am 12:08 AM

PHP is a scripting language widely used on the server side, especially suitable for web development. 1.PHP can embed HTML, process HTTP requests and responses, and supports a variety of databases. 2.PHP is used to generate dynamic web content, process form data, access databases, etc., with strong community support and open source resources. 3. PHP is an interpreted language, and the execution process includes lexical analysis, grammatical analysis, compilation and execution. 4.PHP can be combined with MySQL for advanced applications such as user registration systems. 5. When debugging PHP, you can use functions such as error_reporting() and var_dump(). 6. Optimize PHP code to use caching mechanisms, optimize database queries and use built-in functions. 7

PHP vs. Python: Understanding the Differences PHP vs. Python: Understanding the Differences Apr 11, 2025 am 12:15 AM

PHP and Python each have their own advantages, and the choice should be based on project requirements. 1.PHP is suitable for web development, with simple syntax and high execution efficiency. 2. Python is suitable for data science and machine learning, with concise syntax and rich libraries.

See all articles