PHP cashing Multi-server sharing SESSION data

Source: Internet
Author: User
Tags php session
PHP enables multi-server sharing SESSION data

first, the origin of the problem
Slightly larger sites, usually have several servers, each server running different functions 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 name and password can be used in each module of the whole website. It is easier to share user data with each server, just put a database server on the back end, each server through the unified connection
Access to user data. However, there is still a problem, that is, after the user logs on to another server after the other module, still need to log back in, this is a login, all through
The problem of the line, mapping to the technology, is actually how each server realizes sharing SESSION data.
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 PHP page being accessed can use
Session_Start () opens the session, which generates the client's unique ID session ID, which can be passed through the function
session_id () get/set). SESSION ID can be retained in the client in two ways, so that when requesting a different page, the PHP program can learn the client's
The session ID is automatically added to the Get URL, or the POST form, by default, the variable is named
PHPSESSID; 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 settings in the php.ini
The session is saved by files (Session.save_handler = files), which is the way to save the session using read-write files
data, and the directory saved by the session file is specified by Session.save_path, and the file name is prefixed with Sess_, followed by the session
ID, such as: sess_c72665af28a8b14c0fe11afe3b59b51b. The data in the file is the SESSION after serialization
The data. If the traffic is large, the session file may be generated more, then you can set up a hierarchical directory for the session
Save the 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
To start the directory. When the session data is written, PHP obtains the client's session_id, and then according to the session ID to the specified
The session file is saved in the directory where the corresponding session file is found, does not exist, it is created, and the data is then serialized and then written to the file. Read SESSION
The data is also a similar operation flow, the reading of the data needs to be deserialized, generating the corresponding SESSION variables.
three, multi-server sharing SESSION of the main obstacles and solutions
By understanding how the session works, we can see that, by default, each server generates a session for the same client individually
ID, such as for the same user browser, the SESSION ID generated by a server is 30de1e9de3192ba6ce2992d27a1b6a0a, and
The B server generates a c72665af28a8b14c0fe11afe3b59b51b. In addition, the SESSION of PHP
The data is stored separately in the file system of the 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 for each server that is generated by the same client
The SESSION ID must be the same and 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. [Color= Green] is simply the session ID of the multi-server shared client and must share the session data on the server side.
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 statements are as follows:
? ? CREATE TABLE ' Sess ' (
? ??? ' Sesskey ' varchar (+) not NULL default ' ',
? ?? ? ' expiry ' bigint () 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 issues
If 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 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 for data reading and writing, 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?

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