A method based on Redis to process sessions, as follows.
<?php class Session_custom {private $redis;//Redis instance private $prefix = ' sess_ ';//session_id prefix//session start, will
To execute this method, connect the Redis Server public function open ($path, $name) {$this->redis = new Redis ();
return $this->redis->connect ("127.0.0.1", 6379);
At the end of the//session, call this method to turn off the Redis connection public function close () {$this->redis->close ();
return true; This method is called when the session saves data, and the public function write ($session _id, $data) is called after the script finishes or session_write_close the method call $this-&
Gt;redis->hmset ($this->prefix. $session _id, Array (' Expires ' => time (), ' data ' => $data));
///After starting the session automatically or by calling the Session_Start () function, PHP internally calls the read callback function to get session data. Public function read ($session _id) {if ($this->redis->exists ($this->prefix. $session _id)) {return $this-
>redis->hget ($this->prefix. $session _id, ' data ');
} return ';
//Clears the data in the session, this callback function is called when the Session_destroy () function is invoked, or when the session_regenerate_id () function is invoked, and the destroy parameter is set to TRUE. Public function Destroy ($session _id) {if ($this->redis->exists ($this->prefix. $session _id)) {return $t His->redis->del ($this->prefix. $session _id) > 0?
True:false;
return true; }//garbage collection function, the invocation cycle is controlled by the session.gc_probability and Session.gc_divisor parameters Public function gc ($maxlifetime) {$allKeys
= $this->redis->keys ("{$this->prefix}*"); foreach ($allKeys as $key) {if ($this->redis->exists ($key) && $this->redis->hget ($key, ' expires ')
+ $maxlifetime < time ()) {$this->redis->del ($key);
} return true;
}//Call the custom session processing Method $handler = new Session_custom (); Session_set_save_handler (Array ($handler, ' open '), array ($handler, ' close '), Array ($handler, ' read '), Array ($handl
Er, ' write '), array ($handler, ' destroy '), Array ($handler, ' GC ')); The following line of code prevents the unintended behavior that may be raised when an object is saved as a session Save manager, indicating that the current session data is stored and the current session is closed after the script executes or after calling exit () register_shutdown_function (' Session_ Write_close ');
Session_Start ();
You can use the session
Add:
The session.gc_probability in the php.ini file together with the Session.gc_divisor two configuration options determine the timing of GC function calls. The default values are divided into 1 and 1000, which means that each request has only 1/1000 chance to invoke the GC function.
The above is the entire content of this article, I hope to help you learn.