PHP implementation of multi-server sharing SESSION Data _php tutorial

Source: Internet
Author: User
Tags php session
first, the origin of the problem
Slightly larger sites, usually have several servers, each server running a different function of the module, the use of different two-level domain names, and a strong overall site, the user system is unified, that is, a set of user names, passwords in the entire site of the various modules can be logged in use. Each server sharing user data is relatively easy to implement, only need to put a database server on the back end, each server through the unified interface to access user data. However, there is still a problem, that is, after the user login to another server after the other module, still need to log back in, this is a login, all the problems, mapping to the technology, in fact, how each server to achieve sharing SESSION data problem.
Ii. How the PHP SESSION works
Before you solve the problem, let's look at how the PHP SESSION works. When a client (such as a browser) logs on to a Web site, the accessed PHP page can use Session_Start () to open the session, which results in a client's unique ID session ID (this ID can be obtained/set through the function session_id). Session ID can be retained in two ways in the client, so that when requesting a different page, the PHP program can learn the client's session ID, one is to automatically add session ID to the Get URL, or POST form, by default, the variable name is P Hpsessid; the other is to save the SESSION ID in a cookie by using a cookie, by default, the name of the cookie is PHPSESSID. Here we mainly explain in the COOKIE way, because the application is more extensive.
So where does the SESSION data be stored? It is, of course, on the server side, but not in memory, but in a file or database. By default, the session set in PHP.ini is saved by files (Session.save_handler = files), that is, the session data is saved using a read-write file, and the directory saved by the session file is SESSION.S AVE_PATH specifies that the file name is prefixed with Sess_, followed by the SESSION ID, such as: sess_c72665af28a8b14c0fe11afe3b59b51b. The data in the file is the SESSION data after the serialization. If the access volume is large, may produce the session file will be more, then you can set the hierarchical directory to save the session file, the efficiency will be improved a lot, the setting method is: Session.save_path= "N;/save_path", N is a graded series, save _path is the starting directory. When the session data is written, PHP will obtain the client's session_id, and then according to the session ID to the specified session file to save the directory to find the corresponding session file, does not exist to create, and finally to serialize the data to write to the file. Reading session data is a similar process, and the data that is read needs to be deserialized to generate the corresponding session variables.
three, multi-server sharing SESSION of the main obstacles and solutions
By understanding how the session works, we can find that, by default, each server generates session IDs for the same client individually, such as the session ID generated by a server for the same user browser. 30DE1E9DE3192BA6CE2992D27A1B6A0A, while the B server generates C72665AF28A8B14C0FE11AFE3B59B51B. In addition, the SESSION data of PHP is stored separately in the file system of this server. As shown in the following:


Once you have identified the problem, you can proceed with the solution. To share session data, two goals must be achieved: one is that each server must have the same session ID as the same client, and it can be passed through the same COOKIE, which means that each server must be able to read the same name as PHPSESSID. A COOKIE; the other is how the SESSION data is stored/placed to ensure that each server has access to it.
In Short, the session ID of the multi-server shared client, and the server-side session data must also be shared.
The first goal of the implementation is very simple, only need to set the domain of the cookie is special, by default, the domain of the cookie is the domain name/IP address of the current server, and the domain is different, the individual servers set cookies are not accessible to each other, such as
www.aaa.com
The server is unable to read and write
www.bbb.com
The server sets the COOKIE. Here we say that the server of the same site has its particularity, that is, they belong to the same domain, such as: Aaa.infor96.com and
www.infor96.com
belong to the domain. infor96.com, then we can set the cookie domain to. infor96.com so that aaa.infor96.com, www.infor96.com, and so on can access this cookie. The Setup method in the PHP code is as follows:
(' Session.cookie_domain ', '. infor96.com ');
?>
The purpose of each server sharing the same client SESSION ID is achieved.
The implementation of the second goal can use file sharing, such as NFS, but the setup, operation is somewhat complex. We can refer to the previous method of unified user system, that is, using a database to save session data, so that each server can easily access the same data source, to obtain the same session data.
The workaround is as follows:


Iv. Implementation of the Code
First create the data table, MySQL SQL statement is as follows: Create TABLE ' Sess ' (
' Sesskey ' varchar (+) not NULL default ' ',
' Expiry ' bigint (a) Not NULL default ' 0 ',
' Data ' longtext not NULL,
PRIMARY KEY (' Sesskey '),
KEY ' expiry ' (' expiry ')
) Engine=myisam DEFAULT Charset=utf8 collate=utf8_unicode_ci
Sesskey for session Id,expiry, data is used to save session data.
By default, session data is saved as a file and you want to save it as a database, you must redefine the handler functions for each operation of the session. PHP provides a
Session_set_save_handle ()
function, you can use this function to customize the process of the SESSION, of course, first of all to change the Session.save_handler to user, can be set in PHP:
(' user ');
?>
Next, focus on the Session_set_save_handle () function, which has six parameters: Session_set_save_handler (string Open, string close, string read, string Write, string destroy, String gc)
Each parameter is a function name for each operation: Open, close, read, write, destroy, garbage collection. There are detailed examples in the PHP manual, where we use OO methods to implement these operations, the detailed code is as follows:
(' My_sess_time ', 3600); SESSION Survival Duration
Class definition
Class My_sess
{
function init ()
{
$domain = '. infor96.com ';
Do not use Get/post variable mode
Ini_set (' Session.use_trans_sid ', 0);
Set the maximum time to live for garbage collection
Ini_set (' Session.gc_maxlifetime ', my_sess_time);
How to save SESSION ID using a COOKIE
Ini_set (' session.use_cookies ', 1);
Ini_set (' Session.cookie_path ', '/');
Multi-host sharing COOKIE that holds 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 name that corresponds to each operation of the SESSION:
Session_set_save_handler (
Array (' my_sess ', ' open '),//corresponds to static method My_sess::open (), same as 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) {//Close database connection
$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 session data corresponding to 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; Set 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
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. Time ();
$MY _sess_conn->execute ($sql);
Due to frequent deletion of the table sess, it is easy to produce fragments,
Therefore, the table is optimized for 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 ');
A database configuration item that can be placed in a 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, which 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 run before session_start ()!!
My_sess::init ();
?>
v. Legacy issuesIf the site has a large number of visits, the session will be read and written frequently to the database operation, so the efficiency will be significantly reduced. Considering that the session data is generally not very large, you can try to write a multi-threaded program with C/java, the HASH table to save session data, and through the socket communication data read and write, so that the SESSION is stored in memory, read and write speed should be much faster. Load balancing can also be used to offload server load. But these are just some of my own ideas and assumptions that have not been practiced

http://www.bkjia.com/PHPjc/320377.html www.bkjia.com true http://www.bkjia.com/PHPjc/320377.html techarticle first, the problem originates slightly larger website, usually has several servers, each server runs the different function module, uses the different two level domain name, but a whole strong net ...

  • 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.