ThinkPHP custom Redis SESSION processing implementation method, thinkphpredis
This article describes how ThinkPHP can customize Redis to Process sessions. We will share this with you for your reference. The details are as follows:
In daily use, session is used to store user login information. Common session storage methods include file storage (default), database storage, Redis storage, and memcached. Here we mainly record the usage of using Redis to save sessions when processing sessions with ThinkPHP.
1. Define in configuration items:
'Session _ type' => 'redis ', // SESSION storage TYPE 'session _ prefix' => 'sess _', // session prefix 'redis _ host' => '100. 0.0.1 '// REDIS server address 'redis _ port' => 6379, // REDIS connection PORT number 'session _ EXPIRE' => 3600, // SESSION expiration time
You can find the method for defining the session in the ThinkPHP/Common/functions. php file, and read the judgment of the session driver in about 1179 lines. If SESSION_TYPE is defined, a new Redis object is created and the session storage function session_set_save_handler () is called ().
2. Create the Redis. class. php file in the ThinkPHP \ Library \ Think \ Session \ Driver directory.
The file content is as follows:
<? Phpnamespace Think \ Session \ Driver; class Redis {// Redis connection object private $ redis; // Session expiration time private $ expire; /*** open method * @ param type $ path * @ param type $ name * @ return type */public function open ($ path, $ name) {$ this-> expire = C ('session _ EXPIRE ')? C ('session _ EXPIRE '): ini_get ('session. gc_maxlifetime'); $ this-> redis = new Redis (); return $ this-> redis-> connect (C ('redis _ host '), C ('redis _ port');}/*** close * @ return type */public function close () {return $ this-> redis-> close ();}/*** read * @ param string $ id * @ return type */public function read ($ id) {$ id = C ('session _ prefix '). $ id; $ data = $ this-> redis-> get ($ id); return $ data? $ Data: '';}/*** write * @ param string $ id * @ param type $ data * @ return type */public function write ($ id, $ data) {$ id = C ('session _ prefix '). $ id; return $ this-> redis-> set ($ id, $ data, $ this-> expire );} /*** destroy * @ param string $ id */public function destroy ($ id) {$ id = C ('session _ prefix '). $ id; $ this-> redis-> delete ($ id );} /*** garbage collection ** @ param type $ maxLifeTime * @ return boolean */public function gc ($ maxLifeTime) {return true ;}}
So far, Redis has completed session processing.
The memcached method is similar to that of Redis!
Supplement: The editor recommends a php formatting and formatting typographical tool on this site to help you typeset code in future PHP programming:
Php code online formatting and beautification tools:Http://tools.jb51.net/code/phpformat