PHP allows multiple web servers to share SESSION data-writing session data to mysql databases

Source: Internet
Author: User
Tags php session
PHP allows multiple web servers to share SESSION data (write session data to mysql database) I. websites with a slightly larger problem generally have several servers, each of which runs modules with different functions, different second-level domain names are used, while the user system of a website with a strong integrity is unified, that is, a set of user names and passwords are located across the entire website. "> <LINKhref =" http: // www.

PHP allows multiple web servers to share SESSION data (write session data to mysql database)

I. problem origin

Websites with a slightly larger size usually have several servers. each server runs modules with different functions and uses different second-level domain names. The User System of a website with a strong integrity is unified, that is, a user name and password can be used to log on to each module of the entire website. Sharing user data between servers is easy to implement. you only need to set up a database server on the backend. each server can access user data through a unified interface. However, there is still a problem, that is, the user still needs to log on again after logging on to the server and entering another module of the server. this is a logon and all traffic problems, ing to the technology is actually a question about how each server shares SESSION data.

II. working principles of PHP sessions

Before solving the problem, let's take a look at the working principles of the php session. When a client (such as a browser) logs on to a website, you can use session_start () to open the SESSION on the Accessed PHP page, this will generate a unique session id of the client (this ID can be obtained/set through the session_id () function ). The session id can be retained on the client in two ways, so that the PHP program can obtain the session id of the client when requesting different pages; one is to automatically add the session id to the get url (this can only be implemented in unix systems, but not in windows systems), or in the POST form, by default, the variable name is PHPSESSID. The other is to store the session id in the COOKIE through COOKIE. by default, the COOKIE name is PHPSESSID. Here we mainly describe the COOKIE method, because it is widely used.

Where can SESSION data be stored? Of course, it is on the server side, but not stored in the memory, but saved in a file or database. By default, the SESSION storage method set in php. ini is

Files (session. save_handler = files), that is, SESSION data is saved by reading and writing files. The Directory saved by the SESSION file is specified by session. save_path, and the file name is

Sess _ is the prefix followed by the session id, for example, sess_c000065af28a8b14c0fe11afe3b59b51b. The data in the file is the serialized SESSION data. If the traffic volume is large

There will be a large number of SESSION files. in this case, you can set a hierarchical directory to save SESSION files, which improves the efficiency by setting session. save_path = "N;/save_path", where N is a hierarchical level.

, Save_path is the start directory. When writing SESSION data, PHP will get the SESSION_ID of the client, and then find it in the specified SESSION file storage directory based on the session id.

If the SESSION file does not exist, it is created. The data is 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

SESSION variable.

III. main obstacles and solutions to multi-server SESSION sharing

By understanding the working principle of the SESSION, we can find that by default, each server generates a session id for the same client, for example, for the same user browser, the session id generated by server A is 30de1e9de3192ba6ce2992d27a1b6a0a, while that generated by server B is c000065af28a8b14c0fe11afe3b59b51b. In addition, the SESSION data of PHP is stored in the file system of the current server.

After confirming the problem, you can start to solve it. To share SESSION data, you must achieve the following two goals:

One is that the SESSION IDs generated by each server on the same client must be the same and can be passed through the same COOKIE. that is to say, each server must be able to read the same phpsessid cookie;

The other is the storage mode/location of SESSION data, which must be accessible to all servers. Simply put, multiple servers share the session id of the client, and must also share the session id of the server.

Data.

The implementation of the first target is actually very simple. you only need to set the COOKIE domain. by default, the COOKIE domain is the domain name/IP address of the current server, if the domain is different

The cookies set by servers cannot access each other.

IV. code implementation

First, create a data table. the MySQL SQL statement is as follows:

Create table 'sess '(

'Sskey' varchar (32) not null default '',

'Expiry' bigint (20) not null default '0 ',

'Data' longtext not null,

Primary key ('sskey'), 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 as files. to save data as a database, 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. you can set session_module_name ('user') in PHP ');

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 name of the function for each operation, these operations are as follows:

Open, close, read, write, destroy, and recycle. The PHP manual contains detailed examples,

Here we use the OO method to implement these operations. the detailed code is as follows:

  

Define ('My _ SESS_TIME ', 3600); // SESSION survival duration

// Class definition

Class My_Sess

{

/**

* The database connection object is set to a static variable. because it is not set to a static variable, the database connection object cannot be called in other methods. why is it unknown?

*

* @ Var obj

*/

Static public $ db;

/**

* Constructor

*

* @ Param obj $ dbname database connection object

*/

Function _ construct ($ dbname ){

Self: $ db = $ dbname;

}

/**

* Initialize the session and use the mysql database to store the session value. it is implemented using session_set_save_handler.

*

*/

Function init ()

{

$ Domain = '';

// Do not use the GET/POST variable method

Ini_set ('session. use_trans_sid ', 0 );

// Set the maximum time to live for garbage collection

Ini_set ('session. gc_maxlifetime ', MY_SESS_TIME );

// Use cookies to save SESSION IDs

Ini_set ('session. use_cookies ', 1 );

Ini_set ('session. cookie_path ','/');

// Multiple hosts share the COOKIE used to save the session id. because I tested the SESSION ID on a local server, 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 name corresponding to each SESSION operation

Session_set_save_handler (

Array ('My _ sess', 'open'), // corresponds to the open () method of the class My_Sess, the same below.

Array ('My _ sess', 'close '),

Array ('My _ sess', 'read '),

Array ('My _ sess', 'write '),

Array ('My _ sess', 'deststroy '),

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 the SESSION data corresponding to the SESSION ID

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

$ Rs-> close ();

Return $ v;

}

}

Return '';

}

Function write ($ sesskey, $ data ){

$ Qkey = $ sesskey;

$ Expiry = time () + MY_SESS_TIME;

$ Arr = array (

'Sskey' => $ qkey,

'Expiry' => $ expiry,

'Data' => $ data );

Self: $ db-> replace ('sss', $ arr, 'sskey', 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 table sess, fragments are easily generated,

// Optimize the table in garbage collection.

$ SQL = 'optimize TABLE 'SS '';

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

Return true;

}

}

// Use ADOdb as the database abstraction layer.

Require_once ('adodb/adodb. inc. php ');

// Database configuration items, which can be placed in the configuration file (for example, config. inc. php ).

$ Db_type = 'mysql ';

$ Db_host = '2017. 0.0.1 ';

$ Db_user = 'root ';

$ Db_pass = '123 ';

$ Db_name = 'sess _ db ';

// Create a database connection.

$ Cnn = & ADONewConnection ($ db_type );

$ Cnn-> Connect ($ db_host, $ db_user, $ db_pass, $ db_name );

// Initialize the SESSION settings. the initialization contains session_start ()!

$ Sess = new My_Sess ($ cnn );

$ Sess-> init ();

$ _ SESSION ['A'] = 'aaa ';

$ _ SESSION ['B'] = 'BBB ';

$ _ SESSION ['c'] = 'CCC ';

Print_r ($ _ SESSION );

?>

5. legacy problems if the website has a large access volume, SESSION read/write operations will be performed frequently on the database, which will significantly reduce the efficiency. Considering that the SESSION data is usually not very large, you can try to use

C/Java writes a multi-threaded program, saves SESSION data in the HASH table, and reads and writes data through socket communication, so that the SESSION is saved in the memory, and the read and write speed should be much faster. You can also

Server load balancing.

Finally, attach the session execution graph analyzed by yourself based on the above instance execution

  

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.