Home > Backend Development > PHP Tutorial > PHP implements multiple web servers to share SESSION data-session data is written to mysql database_PHP tutorial

PHP implements multiple web servers to share SESSION data-session data is written to mysql database_PHP tutorial

WBOY
Release: 2016-07-13 17:39:34
Original
824 people have browsed it

PHP enables multiple web servers to share SESSION data (session data is written to the mysql database)

1. Origin of the problem

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 The user name and password can be used to log in to all modules of the entire website. It is relatively easy for each server to share user data. 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.

2. How PHP SESSION works

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 when requesting different pages, the PHP program can learn the client's SESSION ID; one is to automatically add the SESSION ID to the GET URL (this can only be done under Unix systems) (The Windows system cannot automatically add it to the URL), or in the POST form. By default, the variable name is PHPSESSID; the other is to save the SESSION ID in the COOKIE through COOKIE. By default, the name of this COOKIE is the PHPSESSID. Here we mainly use the COOKIE method for explanation, because it is widely used.

So where is the SESSION data stored? Of course it is on the server side, but it is not stored 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, saving SESSION data by reading and writing files, and the directory where SESSION files are 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 there is a large number of visits,

may occur

There will be more SESSION files. In this case, you can set up a hierarchical directory to save SESSION files. The efficiency will be much improved. The setting method is: session.save_path="N;/save_path", N is the number of hierarchical levels

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

in the specified SESSION file saving directory.

The corresponding SESSION file will be created if it does not exist. Finally, the data will be serialized and written to the file. Reading SESSION data is a similar operation process. The read data needs to be deserialized to generate the corresponding

’s SESSION variable.

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.

After identifying the problem, you can start to solve 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 COOKIE named PHPSESSID;

Another 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 they must also share the server's SESSION

Data.

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

COOKIES set by two servers cannot access each other.

IV. Code implementation

First create a data table. The SQL statement of MySQL 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=MyISAM

 Sesskey is the SESSION ID, expiry is the SESSION expiration time, and data is used to save SESSION data.

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

Next, we will 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 in order:

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

 {

 /**

 * The database connection object is set as a static variable. Because it is not set as a static variable, the database connection object cannot be called in other methods. It is still unclear why

*

 * @var obj

*/

static public $db;

 /**

 * Constructor

*

* @param obj $dbname database connection object

*/

Function __construct($dbname){

Self::$db = $dbname;

 }

 /**

* Initialize the session, use the database mysql to store the session value, and use the session_set_save_handler method to implement

*

*/

Function init()

 {

 $domain = ;

//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. Because I am testing on a local server, I set $domain=

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 open() method of class My_Sess, the same below.

array(My_Sess,close),

array(My_Sess,read),

array(My_Sess,write),

array(My_Sess,destroy),

array(My_Sess,gc)

 );

//session_start() must be located after the session_set_save_handler method

session_start();

 }

Function open($save_path, $session_name) {

//print_r($sesskey);

return true;

 } //end function

Function close(){

 if(self::$db){

Self::$db->close();

 }

return true;

 }

Function read($sesskey) {

 $sql = SELECT `data` FROM `sess` WHERE `sesskey`= . (self::$db->qstr($sesskey)) . AND `expiry`>= . time();

 $rs=self::$db->execute($sql);

 if($rs){

 if($rs->EOF){

return ;

 } else {//Read SESSION data corresponding to SESSION ID

 $v = $rs->fields[0];

 $rs->close();

return $v;

 }

 }

return ;

 }

Function write($sesskey,$data){

 $qkey = $sesskey;

$expiry = time()+MY_SESS_TIME;

 $arr = array(

 sesskey => $qkey,

expiry => $expiry,

data => $data);

Self::$db->replace(sess, $arr, sesskey, true);

return true;

 }

Function destroy($sesskey) {

 $sql = DELETE FROM `sess` WHERE `sesskey`=.self::$db->qstr($sesskey);

 $rs =self::$db->execute($sql);

return true;

 }

Function gc($maxlifetime = null) {

 $sql = DELETE FROM `sess` WHERE `expiry`<.time();

Self::$db->execute($sql);

// Due to frequent deletion operations on the sess table, fragmentation is easy to occur,

//So optimize the table during garbage collection.

 $sql = OPTIMIZE TABLE `sess`;

Self::$db->Execute($sql);

www.bkjia.comtruehttp: //www.bkjia.com/PHPjc/486277.htmlTechArticlePHP implements multiple web servers to share SESSION data (session data is written to the mysql database) 1. The origin of the problem is slightly larger Websites usually have several servers, each server running...
source:php.cn
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template