search
HomeBackend DevelopmentPHP TutorialPHP shares SESSION operations on different servers_PHP tutorial
PHP shares SESSION operations on different servers_PHP tutorialJul 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怎么把负数转为正整数php怎么把负数转为正整数Apr 19, 2022 pm 08:59 PM

php把负数转为正整数的方法:1、使用abs()函数将负数转为正数,使用intval()函数对正数取整,转为正整数,语法“intval(abs($number))”;2、利用“~”位运算符将负数取反加一,语法“~$number + 1”。

php怎么实现几秒后执行一个函数php怎么实现几秒后执行一个函数Apr 24, 2022 pm 01:12 PM

实现方法:1、使用“sleep(延迟秒数)”语句,可延迟执行函数若干秒;2、使用“time_nanosleep(延迟秒数,延迟纳秒数)”语句,可延迟执行函数若干秒和纳秒;3、使用“time_sleep_until(time()+7)”语句。

php字符串有没有下标php字符串有没有下标Apr 24, 2022 am 11:49 AM

php字符串有下标。在PHP中,下标不仅可以应用于数组和对象,还可应用于字符串,利用字符串的下标和中括号“[]”可以访问指定索引位置的字符,并对该字符进行读写,语法“字符串名[下标值]”;字符串的下标值(索引值)只能是整数类型,起始值为0。

php怎么除以100保留两位小数php怎么除以100保留两位小数Apr 22, 2022 pm 06:23 PM

php除以100保留两位小数的方法:1、利用“/”运算符进行除法运算,语法“数值 / 100”;2、使用“number_format(除法结果, 2)”或“sprintf("%.2f",除法结果)”语句进行四舍五入的处理值,并保留两位小数。

php怎么读取字符串后几个字符php怎么读取字符串后几个字符Apr 22, 2022 pm 08:31 PM

在php中,可以使用substr()函数来读取字符串后几个字符,只需要将该函数的第二个参数设置为负值,第三个参数省略即可;语法为“substr(字符串,-n)”,表示读取从字符串结尾处向前数第n个字符开始,直到字符串结尾的全部字符。

php怎么根据年月日判断是一年的第几天php怎么根据年月日判断是一年的第几天Apr 22, 2022 pm 05:02 PM

判断方法:1、使用“strtotime("年-月-日")”语句将给定的年月日转换为时间戳格式;2、用“date("z",时间戳)+1”语句计算指定时间戳是一年的第几天。date()返回的天数是从0开始计算的,因此真实天数需要在此基础上加1。

php怎么替换nbsp空格符php怎么替换nbsp空格符Apr 24, 2022 pm 02:55 PM

方法:1、用“str_replace(" ","其他字符",$str)”语句,可将nbsp符替换为其他字符;2、用“preg_replace("/(\s|\&nbsp\;||\xc2\xa0)/","其他字符",$str)”语句。

php怎么查找字符串是第几位php怎么查找字符串是第几位Apr 22, 2022 pm 06:48 PM

查找方法:1、用strpos(),语法“strpos("字符串值","查找子串")+1”;2、用stripos(),语法“strpos("字符串值","查找子串")+1”。因为字符串是从0开始计数的,因此两个函数获取的位置需要进行加1处理。

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

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
3 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
3 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. How to Fix Audio if You Can't Hear Anyone
3 weeks agoBy尊渡假赌尊渡假赌尊渡假赌

Hot Tools

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

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.

SAP NetWeaver Server Adapter for Eclipse

SAP NetWeaver Server Adapter for Eclipse

Integrate Eclipse with SAP NetWeaver application server.

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

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),