Session is saved to the cache (Redis), DB

Source: Internet
Author: User
Tags php session unique id

Why do you want to save the session in the cache

As far as PHP is concerned, the session supported by the language itself is saved to the disk file in a file, saved in the specified folder, the saved path can be set in the configuration file or in the program using function Session_save_path (), but there is a disadvantage,

The first is to save to the file system, inefficient, as long as the usefulness of the session will be from a number of files to find the specified SessionID, inefficient.

The second is that when using more than one server may appear, the session lost problem (in fact, is saved on the other server).

Of course, saving in the cache can solve the above problem, if you use the PHP itself session function, you can use the Session_set_save_handler () function is convenient to the session of the processing process to re-control. If you do not use the PHP session series functions, you can write a similar session function, it is also possible, I am doing this project is this, will be based on the user's mid, login time to hash as SessionID, Each request must add SessionID to be considered legal (when the first login is not required, this time will create SessionID, return to the client), so it is very convenient, concise and efficient. Of course, this article is mainly about the PHP itself in the session "do the Dirty."

Session is saved in the cache

PHP to save the cache to Redis, you can use the configuration file, the session processing and save to make changes, of course, in the program using the Ini_set () function to modify also can, this is very convenient to test, I use this method here, of course, if the production environment is recommended to use the configuration file.

<?PHPIni_set("Session.save_handler", "Redis");Ini_set("Session.save_path", "tcp://localhost:6379");Session_Start();Header("Content-type:text/html;charset=utf-8");if(isset($_session[' View '])){    $_session[' view '] =$_session[' View '] + 1;}Else{    $_session[' view '] = 1;}Echo"View" {$_session[' View ']} ";

Here the Session.save_handler is set to Redis,session.save_path as the address and port of Redis, set to refresh later, and then look back at Redis, and you will find the SessionID generated in Redis, SessionID and browser requests are the same,

is not very convenient, only need to change the configuration file can be implemented in Redis to save the session, but I would like to say here is the way to process the session by the program to save to Redis or DB, the next look.

Overwrite the session's handler function with PHP's interface

Here we can first look at the PHP function session_set_save_handler,php5.4 and then directly implement the Sessionhandlerinterface interface, the code will be more concise. There are several ways to rewrite the main

Open (String $savePath, string $sessionName); Open is similar to a constructor, which is called when a session is started, such as after using the Session_Start () function

Close (); A destructor similar to a class that is called after the write function is called, after which Session_write_close () executes

Read (string $sessionId); Called when the session is read

Write (string $sessionId, string $data); When you save the data, call

Destory ($SESSIONID); When the session is destroyed (Session_destory () or session_regenerate_id ()) calls

GC ($LIFETIME); Garbage cleanup function to clean up outdated obsolete data

Mainly to achieve these methods, according to different storage drivers can set different specific methods, I realized the MySQL database and redis the two save session driver, if necessary, can expand themselves, the extension is very easy.

Here's my Redis implementation (DB and Redis are similar, Redis code is less, post it):

I use the way of the interface, so that it is more convenient to expand, the day I want to use memcached, directly added on the line

<?PHPinclude_once__dir__. " /interfacesession.php ";/** * Save session in DB mode*/classRedissessionImplementsinterfacesession{/** * Save the information of the Session database table*/    Private $_options=Array(        ' Handler ' =NULL,//database connection handle' Host ' =NULL, ' Port ' =NULL, ' lifeTime ' =NULL,    ); /** * constructor * @param $options set information array*/     Public function__construct ($options=Array()){        if(!class_exists("Redis",false)){             die("Redis extensions must be installed"); }        if(!isset($options[' LifeTime ']) ||$options[' LifeTime '] <= 0){            $options[' lifeTime '] =Ini_get(' Session.gc_maxlifetime '); }        $this->_options =Array_merge($this->_options,$options); }    /** * Start the session with this driver*/     Public functionbegin () {if($this->_options[' host '] = = =NULL||$this->_options[' port ' = = = =NULL||$this->_options[' lifeTime '] = = =NULL        ){            return false; }        //Set Session handler function        Session_set_save_handler(            Array($this, ' open '),Array($this, ' close '),Array($this, ' read '),Array($this, ' write '),Array($this, ' Destory '),Array($this, ' GC ')        ); }    /** * Automatically start answering or session_start () the first function called after starting a call * is similar to the function of a constructor * @param $savePath the default save path * @param $sessionName Default parameter name, PHPSESSID*/     Public functionOpen$savePath,$sessionName){        if(Is_resource($this->_options[' handler '))return true; //Connect to Redis        $redisHandle=NewRedis (); $redisHandle->connect ($this->_options[' Host '],$this->_options[' Port ']); if(!$redisHandle){            return false; }        $this->_options[' handler '] =$redisHandle; $this-&GT;GC (NULL); return true; }    /** * Similar to destructors, called after write or after the Session_write_close () function*/     Public functionClose () {return $this->_options[' Handler ']->Close (); }    /** * Read session information * @param $sessionId uniquely determine the corresponding session data by this ID * @return Session information/empty string*/     Public functionRead$sessionId){        return $this->_options[' Handler ']->get ($sessionId); }    /** * Write or modify session data * @param $sessionId the ID of the session to which the data is to be written @param $sessionData the data to be written is serialized.*/     Public functionWrite$sessionId,$sessionData){        return $this->_options[' Handler ']->setex ($sessionId,$this->_options[' LifeTime '),$sessionData); }    /** * Actively destroying session sessions * @param $sessionId Unique ID of the session to be destroyed*/     Public functionDestory ($sessionId){        return $this->_options[' Handler ']->delete ($sessionId) >= 1?true:false; }    /** * Clean up expired data in painting * @param validity period*/     Public functiongc$lifeTime){        //get all the SessionID, let the expired release out        $this->_options[' handler ']->keys ("*"); return true; }}

See Simple Factory mode

classSession {/** * Driver handle Save*/    Private Static $_handler=NULL; /** * Create session driver*/     Public Static functionGetSession ($type,$options){        //Single Case        if(isset($handler)){            returnSelf::$_handler; }        Switch($type) {             Case' DB '://database-driven session type                    include_once__dir__. " /driver/dbsession.php "; $handler=NewDbsession ($options);  Break;  Case' Redis '://Redis driver Session type                    include_once__dir__. " /driver/redissession.php "; $handler=NewRedissession ($options);  Break; default:return false;  Break; }        returnSelf::$_handler=$handler; }}

Invocation is also very simple,

Session::getsession (' Redis ',array(        ' host ' = ' "localhost",        ' port ' = "6379",     ),begin (); Session_Start ();

Database version of the same is very simple to configure, if necessary, you can download the full version and demo

The copyright belongs to the author Iforever ([email protected]) all, without the author's consent to prohibit any form of reprint, reproduced article must be in the article page obvious location to the author and the original text connection, otherwise reserve the right to pursue legal responsibility.

Session is saved to the cache (Redis), DB

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