Share SESSION data with multiple web servers in PHP _ PHP Tutorial

Source: Internet
Author: User
Tags php session php define
PHP allows multiple web servers to share SESSION data. I. websites with a slightly larger problem usually have several servers. each server runs modules with different functions and uses different second-level domain names, while a network with a strong integrity I. problem originWebsites 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 or the POST form. by default, the variable name is PHPSESSID, and the other is through COOKIE, save the session id in the 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, php. the SESSION storage method set in ini is files (session. save_handler = files), that is, SESSION data is saved by reading and writing files, and the SESSION file directory is saved by session. save_path is specified. the file name is prefixed with sess _ and 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, many SESSION files may be generated. you can set a hierarchical directory to store SESSION files, which improves the efficiency. the setting method is session. save_path = "N;/save_path", where N is the classification level, and save_path is the start directory. When writing SESSION data, PHP will get the SESSION_ID of the client, and then find the corresponding SESSION file in the saved Directory of the specified SESSION file based on the session id. if the SESSION file does not exist, it will be created, finally, 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 sharingBy understanding the working principle of the SESSION, we can find that by default, each server
A client generates a session id. for example, for the same user browser, the session id generated by server A is 30de1e9de3192ba6ce2992d27a1b6a0a, while that generated by server B is c000065af28a8b14c0fe11afe3b59. In addition, the SESSION data of PHP is stored in
In the file system of this server.
After confirming the problem, you can start to solve it. To share SESSION data, you must achieve two goals: one is that the SESSION IDs generated by each server on the same client must be the same and can be transmitted through the same COOKIE, that is to say, each server must be able to read the same COOKIE named PHPSESSID;
The other is the storage mode/location of SESSION data, which must be accessible to all servers. In short, there are many
The session id of the server sharing client, and the SESSION data of the server must also be shared.
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.
The COOKIE set cannot access each other.
IV. code implementationCREATE a data TABLE. the SQL statement of MySQL is as follows: CREATE TABLE 'sss' ('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 session id, expiry indicates the SESSION expiration time. 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 the session_set_save_handle () function, which can be used to customize the SESSION processing process. save_handler is changed 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:
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:

<? Php define ('My _ SESS_TIME, 3600 );
// SESSION survival duration
// Class definition class My_Sess {function init () {$ domain = '.infor96.com ';
// Do not use the GET/POST variable method ini_set ('session. use_trans_sid ', 0 );
// Set the maximum spam life time ini_set ('session. gc_maxlifetime', MY_SESS_TIME );
// Use COOKIE to save session id ('session. use_cookies ', 1 );
Ini_set ('session. cookie_path ','/');
// Multiple hosts share the COOKIE ini_set ('session. cookie_domain ', $ domain) that saves the session id );
// Set session. save_handler to user,
// Instead of the default files session_module_name ('user ');
// Define the method name for each SESSION operation: 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', 'deststroy '),
Array ('My _ sess', 'gc '));}
// End function open ($ save_path, $ session_name) {return true ;}
// End function close () {global $ MY_SESS_CONN; if ($ MY_SESS_CONN ){
// Close the database connection $ MY_SESS_CONN-> Close ();} return true ;}
// End 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 write ($ sesskey, $ data) {global $ MY_SESS_CONN; $ qkey = $ MY_SESS_CONN-> qstr ($ sesskey );
$ Expiry = time () + My_SESS_TIME;
// Set the Expiration Time
// Write SESSION $ arr = array ('sesskey' => $ qkey, 'expiry' => $ expiry, 'data' => $ data );
$ MY_SESS_CONN-> Replace ('sess', $ arr, 'sesskey', $ autoQuote = true );
Return true ;}
// End 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 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, fragments are easily generated,
// Optimize the table in 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, which can be placed in the configuration file (for example, 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 the SESSION settings, which must be run before session_start !! My_Sess: init ();?>
V. legacy issuesIf the website has a large access volume, the SESSION reads and writes the database frequently, which significantly reduces the efficiency. Considering that the SESSION data is generally not very large, you can try to write a multi-threaded program in C/Java, store SESSION data in HASH tables, and perform data read/write through socket communication, in this way, the SESSION will be stored in the memory, and the read/write speed should be much faster. In addition, server load balancing can be used to share the server load.

(Edit responsibility:

Websites with a slightly larger region usually have several servers. each server runs modules with different functions and uses different second-level domain names, while a comprehensive network...

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.