redis/Distributed File storage System/Database storage session, solve the problem of session inconsistency in load Balancing cluster, redissession_php tutorial

Source: Internet
Author: User
Tags sprintf

redis/Distributed File storage System/Database storage session, solve the problem of session inconsistency in load Balancing cluster, redissession

First, the similarities and differences between the session and the cookie

Sessions and cookies are not just a store on the server side, a general

Although the session is stored on the server side, but also needs to match with the client, imagine a browser why the session is always the same (expired or closed not counted), mainly due to the browser side has a cook, called "Phpsessid" Inside this cookie is a string of strings. This string is used to mark the session, when using the session when the server side found this cookie will go to the server side session file directory to find the name "Sess_phpsessid value" of the file (not created), Inside this file is the data stored in the session (serialized data)

So, even if you delete this file, the next time you use the session it will re-create a file of the same name, of course, if the cookie is deleted, it will have to be renamed

Session By default is stored in each server local directory, in ' PHP.ini ' has the corresponding configuration

Server-side configuration:

Session.save_handler = Files (the default is file, defines how the session is saved on the server, file means to save the sesion to a temporary file, if we want to customize the other way to save, such as the database needs to be set to ' user ' )

Session.save_path = "d:/wamp/php/sessiondata/" (defines the location of the temporary file where the server stores the session)

Session.auto_start = 0 (if 1, do not write Session_Start () in each file; session Auto start:)

session.gc_probability = 1

Session.gc_divisor = 100

Session.gc_maxlifetime = 1440 (above three the garbage automatic recovery mechanism which constitutes the session, Session.gc_probability and session.gc_divisor constitute the probability of performing session cleanup, The theoretical explanation is that the service side periodically has a certain probability to call the GC function to clean the session, the probability of cleanup is: Gc_probability/gc_divisor For example: 1/100 indicates that each new session is initialized, 1% of the probability will be recycled by the garbage collection mechanism, The standard for cleanup is the time defined by Session.gc_maxlifetime)

There are also client-related configurations

Session.use_cookies = 1 (SessionID in the client-side storage mode, 1 represents the use of cookies to record the client's SessionID, and $_cookie variable will have $_cookie[' Phpsessionid '] This cookie exists

Session.use_only_cookies = 1 (also defines how the SessionID is stored on the client, and 1 means that only the cookie is used to hold the session ID)

Session.use_trans_sid = 0 (corresponds to the above setting, if this is set to 1, it allows SessionID to pass through the URL parameter, similarly, the recommendation is set to 0, so here to correct some of the questions of the surface Whether disabling cookies can use session, the answer is of course able to set this value to 1)

Session.referer_check = (This setting does not take effect until Session.use_trans_sid = 1, in order to check the HTTP header for "referer" to determine if the session ID contained in the URL is valid, HTTP_ Referer must contain the string specified by this parameter, otherwise the session ID in the URL will be considered invalid. So the general default is empty, i.e. not checked) = PHPSESSID (defines the name of the SessionID, which is the variable name, so the phpsessid=############## in the HTTP header file as seen through the browser HTTP tool)

Session.cookie_lifetime = 0 (Save SessionID Cookie file life cycle, such as 0, for the end of the session, the SessionID disappears automatically, the common forcibly close the browser, will lose the last SessionID)

So, by the above we can know, by default, the session is stored locally on each server, so in a clustered environment if you want to use the session, if you use the default configuration will be the problem, just the customer access a server session file exists a above, However, after a while it may be assigned to the Client B server, when this file does not exist on server B, the data is lost.

That is, the solution is to store the session on a separate server, either the database, or the Redis, or the file server

The author here explains the Setup method

First, using Redis storage session

The author only said that the simplest, do not use a lot of people to write a PHP class rules how to store (of course, you can do so, if in some special needs circumstances)

Modify the php.ini configuration first

Session.save_handler ="tcp://"

Of course, you can also set it in a PHP program.

Ini_set (' Session.save_handler ', ' Redis '); Ini_set (' Session.save_path ', ' tcp:// ');

If you have a password configured in your Redis, you can set this

Session.save_handler = Redissession.save_path = "Tcp://"

Second, use the file server to store the session

This author feel relatively simple, the author of the company directly attached to the Distributed file server to the specified directory, and then access to the Distributed file server like a local folder, just set the next save path

" xxxx "

Third, use the database to store the session

This is slightly more complex, to write a PHP class, specify how to open, read, write, destroy, GC garbage collection, shutdown, but I am not lazy or manually write a meaning

 Phpclasssessionhandler{/** * Library for session storage*/    Constsession_db = ' mytest '; /** * Table stored in session*/    Constsession_table = ' Session '; /** * @var string $_dbhandler database link handle*/    Private $_dbhandler; /** * @var string $_dbhost database host*/    Private $_dbhost; /** * @var string $_dbuser database user name*/    Private $_dbuser; /** * @var string $_dbuser database Password*/    Private $_dbpasswd; /** * @var string $_name session name*/    Private $_name; /** * Constructor * @param string $dbHost Database Host * @param string $dbUser database user name * @param string $dbPasswd database Password * @return void*/     Public function__construct ($dbHost,$dbUser,$dbPasswd)    {        $this->_dbhost =$dbHost; $this->_dbuser =$dbUser; $this-&GT;_DBPASSWD =$dbPasswd; }    /** * Link Database * @param string $savePath Storage path * @param string $name name * @return Boolean*/     Public functionOpen$savePath,$name)    {        $this->_dbhandler =mysql_connect($this->_dbhost,$this->_dbuser,$this-_dbpasswd); if(!$this-_dbhandler) {            return false; }        $this->_name =$name; mysql_select_db(self::session_db,$this-_dbhandler); return true; }    /** * Read session * @param string $sessionId session ID * @return MIXD existence return array otherwise null returned*/     Public functionRead$sessionId)    {        $data= ''; $sql=sprintf(' SELECT ' data ' from '. self::session_table. ' WHERE ' id ' = '%s ',$sessionId); $result=mysql_query($sql,$this-_dbhandler); if(mysql_num_rows($result) = = 1)        {            List($data) =Mysql_fetch_array($result,mysql_num); }        return $data; }    /** * Link Database * @param string $sessionId session ID * @param string $data Data * @return Boolean*/     Public functionWrite$sessionId,$data)    {        $sql=sprintf(                'REPLACE into' . Self::session_table. '(' id ', ' data ', ' Last_time ') VALUES ("%s", "%s",%d)',$sessionId,mysql_escape_string($data), Time()                ); mysql_query($sql,$this-_dbhandler); return mysql_affected_rows($this->_dbhandler) > 0; }    /** * Link database * @param int $expire life cycle * @return Boolean*/     Public functiongc$expire)    {        $sql=sprintf(                        ' DELETE from '. Self::session_table. '' WHERE ' Last_time ' < Now ()-%d',$expire                    ); mysql_query($sql,$this-_dbhandler); return mysql_affected_rows($this->_dbhandler) > 0; }    /** * Close database link * @param void * @return Boolean*/     Public functionClose () {return Mysql_close($this-_dbhandler); }    /** * Destroy session * @param string $sessionId * @return Boolean*/     Public functionDestroy$sessionId)    {        $sql=sprintf(' DELETE from '. self::session_table. ' WHERE ' id ' = '%s ',$sessionId); mysql_query($sql,$this-_dbhandler); $_session=Array(); return mysql_affected_rows($this->_dbhandler) > 0; }}$sessionHandler=NewSessionhandler (' localhost ', ' root ', ' 123abc+ ');Session_set_save_handler(                            Array($sessionHandler, ' open '),Array($sessionHandler, ' close '),Array($sessionHandler, ' read '),Array($sessionHandler, ' write '),Array($sessionHandler, ' Destroy '),Array($sessionHandler, ' GC ')                        );/*In PHP 5.0.5, the write and close callback functions are not invoked until the object is destroyed, so the object cannot be used in either of these callback functions, nor can it throw an exception.     If an exception is thrown in the function, PHP will neither capture it nor track it, which will cause the program to terminate abnormally.    However, the object destructor can use the session.     You can call the Session_write_close () function in a destructor to resolve the problem. But registering the shutdown callback function is a more reliable approach.*/register_shutdown_function(' Session_write_close ');Session_Start();$_session[' test '] = ' AA ';

And then set up a table called session, remember to set up the database first ' mytest ' the Session table has three fields

ID Vchar (+) Primary SessionID primary key

Data Vchar (1000) content (after serialization)

Last_time Int (10) Last modified timestamp

Finished running the contents of the Discovery table

As you can see, this way of customizing the session through the code can be applied not only to the database, but also to other, such as files, Redis, etc.

At this point, the principle of the session, how to customize the session, how to use the session in the cluster, it is finished true techarticle redis/Distributed File storage System/Database storage session, to solve the problem of the session inconsistency in the load Balancing cluster, redissession first of all the similarities and differences between session and cookie session and cookie do not ...

  • Related Article

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