PHP implementation of multi-Web server sharing session data-session data written to MySQL database _php tutorial

Source: Internet
Author: User
Tags php session unique id
PHP enables multiple Web servers to share session data (session data is written to MySQL database)

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 the session ID to the Get URL (this can only be implemented under the UNIX system, Windows system Can not be implemented in the auto-join URL), or POST form, by default, the variable name is PHPSESSID, the other is through a cookie, the SESSION ID is stored in a cookie, by default, the name of this 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? Of course, on the server side, but not in memory, but in the file or database. By default, the SESSION set in PHP.ini is saved by

Files (Session.save_handler = files), that is, the use of read and write files to save session data, and the session file saved directory is specified by Session.save_path, file name to

The Sess_ is prefixed, followed by the SESSION ID, such as: sess_c72665af28a8b14c0fe11afe3b59b51b. The data in the file is the SESSION data after the serialization. If the amount of traffic is large, it may produce

Session file will be more, then you can set up a 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 save directory to find

The corresponding SESSION file, which does not exist, is created, and finally the data is serialized and then written to the file. Reading SESSION data is also a similar operation process, the data that is read out needs to be deserialized, generating the corresponding

The SESSION variable.

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.

Once you have identified the problem, you can proceed with the solution. To share SESSION data, you must achieve two goals:

One is that each server generates the same SESSION ID for the same client and can be passed through the same cookie, which means that each server must be able to read the same cookie named Phpsessid;

The other is how the SESSION data is stored/placed to ensure that each server has access to it. This is simply the session ID of the multi-server shared client, and the server-side session must also be shared

Data.

The first goal of the implementation is very simple, only the domain of the cookie must be specifically set, by default, the domain of the cookie is the domain name/IP address of the current server, and the domain is different,

Cookies that are set by the server cannot be accessed from one another.

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 (a) not NULL default 0,

' Data ' longtext not NULL,

PRIMARY key (' Sesskey '), key ' expiry ' (' expiry ')

) Type=myisam

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 the 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: Session_module_name (user);

Next, 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 The number is the function name for each operation, which in turn is:

Open, close, read, write, destroy, garbage collection. There are detailed examples in the PHP manual,

Here we use OO way to implement these operations, the detailed code is as follows:

  

Define (my_sess_time,3600); SESSION Survival Duration

Class definition

Class My_sess

{

/**

* Database Connection object, set to static variable, because not set to static variable, database connection object can not be called in other methods, it is unclear what reason

*

* @var obj

*/

static public $db;

/**

* Constructor function

*

* @param obj $dbname database Connection object

*/

function __construct ($dbname) {

Self:: $db = $dbname;

}

/**

* Initialize session, use database MySQL to store session value, use Session_set_save_handler method to realize

*

*/

function init ()

{

$domain =;

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 save SESSION ID COOKIE because I am a local server test so set $domain=

Ini_set (Session.cookie_domain, $domain);

Set Session.save_handler to user instead of the default files

Session_module_name (user);

Defines the method name for each operation of the SESSION

Session_set_save_handler (

Array (My_sess,open),//corresponds to the open () method of Class my_sess, 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 of the table sess, it is easy to produce fragments,

Therefore, the table is optimized for garbage collection.

$sql = OPTIMIZE TABLE ' sess ';

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

http://www.bkjia.com/PHPjc/486277.html www.bkjia.com true http://www.bkjia.com/PHPjc/486277.html techarticle PHP Implementation of multi-Web server sharing session data (session data written to MySQL database) One, the problem originated slightly larger sites, usually have several servers, each server running ...

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