search
HomeBackend DevelopmentPHP TutorialPHP shares SESSION operations on different servers_PHP tutorial

PHP shares SESSION operations on different servers_PHP tutorial

Jul 13, 2016 pm 05:52 PM
phpsessiononesuperiordifferentsharedexistoperateserverofwebsiteoriginquestion

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                  $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
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
PHP Email: Step-by-Step Sending GuidePHP Email: Step-by-Step Sending GuideMay 09, 2025 am 12:14 AM

PHPisusedforsendingemailsduetoitsintegrationwithservermailservicesandexternalSMTPproviders,automatingnotificationsandmarketingcampaigns.1)SetupyourPHPenvironmentwithawebserverandPHP,ensuringthemailfunctionisenabled.2)UseabasicscriptwithPHP'smailfunct

How to Send Email via PHP: Examples & CodeHow to Send Email via PHP: Examples & CodeMay 09, 2025 am 12:13 AM

The best way to send emails is to use the PHPMailer library. 1) Using the mail() function is simple but unreliable, which may cause emails to enter spam or cannot be delivered. 2) PHPMailer provides better control and reliability, and supports HTML mail, attachments and SMTP authentication. 3) Make sure SMTP settings are configured correctly and encryption (such as STARTTLS or SSL/TLS) is used to enhance security. 4) For large amounts of emails, consider using a mail queue system to optimize performance.

Advanced PHP Email: Custom Headers & FeaturesAdvanced PHP Email: Custom Headers & FeaturesMay 09, 2025 am 12:13 AM

CustomheadersandadvancedfeaturesinPHPemailenhancefunctionalityandreliability.1)Customheadersaddmetadatafortrackingandcategorization.2)HTMLemailsallowformattingandinteractivity.3)AttachmentscanbesentusinglibrarieslikePHPMailer.4)SMTPauthenticationimpr

Guide to Sending Emails with PHP & SMTPGuide to Sending Emails with PHP & SMTPMay 09, 2025 am 12:06 AM

Sending mail using PHP and SMTP can be achieved through the PHPMailer library. 1) Install and configure PHPMailer, 2) Set SMTP server details, 3) Define the email content, 4) Send emails and handle errors. Use this method to ensure the reliability and security of emails.

What is the best way to send an email using PHP?What is the best way to send an email using PHP?May 08, 2025 am 12:21 AM

ThebestapproachforsendingemailsinPHPisusingthePHPMailerlibraryduetoitsreliability,featurerichness,andeaseofuse.PHPMailersupportsSMTP,providesdetailederrorhandling,allowssendingHTMLandplaintextemails,supportsattachments,andenhancessecurity.Foroptimalu

Best Practices for Dependency Injection in PHPBest Practices for Dependency Injection in PHPMay 08, 2025 am 12:21 AM

The reason for using Dependency Injection (DI) is that it promotes loose coupling, testability, and maintainability of the code. 1) Use constructor to inject dependencies, 2) Avoid using service locators, 3) Use dependency injection containers to manage dependencies, 4) Improve testability through injecting dependencies, 5) Avoid over-injection dependencies, 6) Consider the impact of DI on performance.

PHP performance tuning tips and tricksPHP performance tuning tips and tricksMay 08, 2025 am 12:20 AM

PHPperformancetuningiscrucialbecauseitenhancesspeedandefficiency,whicharevitalforwebapplications.1)CachingwithAPCureducesdatabaseloadandimprovesresponsetimes.2)Optimizingdatabasequeriesbyselectingnecessarycolumnsandusingindexingspeedsupdataretrieval.

PHP Email Security: Best Practices for Sending EmailsPHP Email Security: Best Practices for Sending EmailsMay 08, 2025 am 12:16 AM

ThebestpracticesforsendingemailssecurelyinPHPinclude:1)UsingsecureconfigurationswithSMTPandSTARTTLSencryption,2)Validatingandsanitizinginputstopreventinjectionattacks,3)EncryptingsensitivedatawithinemailsusingOpenSSL,4)Properlyhandlingemailheaderstoa

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

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

VSCode Windows 64-bit Download

VSCode Windows 64-bit Download

A free and powerful IDE editor launched by Microsoft

SublimeText3 English version

SublimeText3 English version

Recommended: Win version, supports code prompts!

SublimeText3 Linux new version

SublimeText3 Linux new version

SublimeText3 Linux latest version

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools