PHP implements redis storage session and phpredissession

Source: Internet
Author: User

PHP implements redis storage session and phpredissession

I. First implement SessionHandlerInterface (this interface is PHP> 5.4.0), as shown below:

<? Php/*** Store sessions in db Mode*/NamespaceOC \ Session;ClassRedisSessionImplements\ SessionHandlerInterface {/*** Save session redis Information*/    Private$ _ Options =Array('Handler' =>Null, // Redis connection handle 'host' =>Null, 'Port' =>Null, 'Lifetime' =>Null,);/*** Constructor*@ Param$ Options: Set an array of information*/    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 to use the driver's session*/    Public functionBegin (){If($ This-> _ options ['host'] =Null| $ This-> _ options ['Port'] =Null| $ This-> _ options ['lifetime'] =Null        ){Return false;} // Sets the session processing function session_set_save_handler (Array($ This, 'open '),Array($ This, 'close '),Array($ This, 'read '),Array($ This, 'write '),Array($ This, 'destory '),Array($ This, 'gc '));}/*** The first called function after automatic start or session_start ()* Functions similar to constructors*@ Param$ SavePath 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 =New\ Redis (); $ redisHandle-> connect ($ this-> _ options ['host'], $ this-> _ options ['Port']);If(! $ RedisHandle ){Return false;} $ This-> _ options ['handler'] = $ redisHandle; $ this-> gc (Null);Return true;}/*** Similar to the destructor, it is called after write or after session_write_close ().*/    Public functionClose (){Return$ This-> _ options ['handler']-> close ();}/*** Read session information*@ Param$ SessionId uniquely identifies the corresponding session data through this Id*@ ReturnSession information/empty string*/    Public functionRead ($ sessionId ){Return$ This-> _ options ['handler']-> get ($ sessionId );}/*** Write or modify session data*@ Param$ SessionId: id of the session to which data is to be written*@ Param$ SessionData: The data to be written has been serialized.*/    Public functionWrite ($ sessionId, $ sessionData ){Return$ This-> _ options ['handler']-> setex ($ sessionId, $ this-> _ options ['lifetime'], $ sessionData );}/*** Actively destroys session*@ Param$ SessionId: Unique id of the session to be destroyed*/    Public functionDestroy ($ sessionId ){Return$ This-> _ options ['handler']-> delete ($ sessionId)> = 1?True:False;}/*** Clear the expired data in the painting.*@ ParamValidity Period*/    Public functionGc ($ lifeTime) {// obtain all sessionids and release expired ones $ this-> _ options ['handler']-> keys ("*");Return true;}}
The above is a complete class for implementing interfaces, which is encapsulated into a file
Ii. Call method:
session_set_save_handler(\OC::$server->getRedisSession(),true);register_shutdown_function('session_write_close');session_start();
That is, calling the session_start () method is equivalent to telling the session storage location to change to redis storage. At this point, all the data stored by the $ _ SESSION method will be automatically put into redis, the key value used for storage is session_id ().
Iii. Explanation:

\OC::$server->getRedisSession()

The above method uses the pimple container to store and call objects. The usage is as follows:

namespace OC;
class Server extends SimpleContainer implements IServerContainer {

Register an object in this server class,

$this->registerService('RedisSession',function (Server $c) {   return new \OC\Session\redisSession(      $c->getSystemConfig()->getValue('redis')   );});
Object retrieval method:

/*** The newly added method for getting user redissession*/Public functionGetRedisSession (){Return$ This-> query ('redissession ');}
Actually
Session_set_save_handler (\ OC ::$ Server-> GetRedisSession (),True);
\OC::$server->getRedisSession()

YesFirst,Class Object in

Reference: http://www.tuicool.com/articles/yeeyume

Copyright Disclaimer: This article is an original article by the blogger and cannot be reproduced without the permission of the blogger.

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.