By default, our PHP stores session data in the form of files. Therefore, each read/write session information needs to access the hard disk.
In order to solve the domain name problem of session information, that is, to achieve a single login at the same time, but also solve the problem that the read/write session information must access the disk, I thought of saving the session to redis.
Below is the code:
Sessionredis: setsessionhandler (); Class sessionredis {public static $ redis; public static function sessionopen ($ savepath, $ sessionname) {self :$ redis = new redis (); self:: $ redis-& gt; Connect (redishost, redisport); self: $ redis-& gt; select (3); Return true;} public static function sessionclose () {return true;} public static function sessionread ($ sessionid) {$ DATA = self: $ redis-& gt; get ($ sessionid); return $ data;} Pu BLIC static function sessionwrite ($ sessionid, $ data) {$ userid = self: getuserid (); If (! Empty ($ userid) {$ ukey = 'uid '. $ userid; If (SELF: $ redis-& gt; hexists ('uid', $ ukey) {$ SSID = self ::$ redis-& gt; hget ('uid', $ ukey); self: sessiondestroy ($ SSID);} self: $ redis-& gt; hset ('uid', $ ukey, $ sessionid);} // $ cache_expire = session_get_cookie_params (); $ cache_expire = ini_get ("session. gc_maxlifetime "); self: $ redis-& gt; setex ($ sessionid, $ cache_expire, $ data); Return true;} public static function sessiondestro Y ($ sessionid) {self: $ redis-& gt; del ($ sessionid); Return true;} public static function sessionGC ($ maxlifetime) {// self :: $ redis-& gt; persist (); Return true;} public static function setsessionhandler () {session_set_save_handler (Array (_ class __, "sessionopen "), array (_ class __, "sessionclose"), array (_ class __, "sessionread"), array (_ class __, "sessionwrite "), array (_ class __, "sessiondestroy"), array (_ class __, "sessio NGC "); Return true;}/* obtain the logon user ID */public static function getuserid () {return isset ($ _ session ['n' _ userid'])? $ _ Session ['n' _ userid']: 0 ;}}
The main purpose is to enable one account to log on only in one place. If the same account is logged on again elsewhere, the session data for the previous login will be cleared!
The code is concise and efficient. It's my style. Haha!
Currently, PHP supports native storage of sessions in redis. Therefore, if you simply save session information to redis, you only need to set it in the PHP configuration file.
session.save_handler = redissession.save_path = "tcp://host1:6379?weight=1, tcp://host2:6379?weight=2&timeout=2.5, tcp://host3:6379?weight=2"
This is OK!