: This article mainly introduces the redis-based session processing method. if you are interested in the PHP Tutorial, please refer to it. A redis-based session processing method is as follows.
1
Redis = new Redis (); 9 return $ this-> redis-> connect ("127.0.0.1", 6379); 10} 1112 // this method is called when the session ends, close redis connection 13 publicfunction close () {14 $ this-> redis-> close (); 15 returntrue; 16} 1718 // this method is called when the session saves data, call 19 publicfunction write ($ session_id, $ data) {20 return $ this-> redis-> hMSet ($ this-> prefix. $ session_id, array ('expires' => time (), 'data' => $ data); 21} 2223 // start the session automatically or call session_sta After the rt () function starts the session manually, PHP calls the read callback function internally to obtain the session data. 24 publicfunction read ($ session_id) {25if ($ this-> redis-> exists ($ this-> prefix. $ session_id) {26 return $ this-> redis-> hGet ($ this-> prefix. $ session_id, 'data'); 27} 28 return ''; 29} 3031 // clear session data. when you call the session_destroy () function, or call session_regenerate_id () this callback function is called when the destroy parameter is set to TRUE. 32 publicfunction destroy ($ session_id) {33if ($ this-> redis-> exists ($ this-> prefix. $ session_id) {34 return $ this-> redis-> del ($ this-> prefix. $ session_id)> 0? True: false; 35} 36 returntrue; 37} 3839 // the garbage collection function. The Call cycle is set by session. gc_probability and session. gc_pisor parameter control 40 publicfunction gc ($ maxlifetime) {41 $ allKeys = $ this-> redis-> keys ("{$ this-> prefix }*"); 42 foreach ($ allKeysas $ key) {43if ($ this-> redis-> exists ($ key) & $ this-> redis-> hGet ($ key, 'expires') + $ maxlifetime <time () {44 $ this-> redis-> del ($ key); 45} 46} 47 returntrue; 48} 49} 5051 // call the custom session processing method 52 $ handler = new Session_custom (); 53session_set_save_handler (54 array ($ handler, 'open '), 55 array ($ handler, 'close'), 56 array ($ handler, 'read'), 57 array ($ handler, 'write'), 58 array ($ handler, 'deststroy'), 59 array ($ handler, 'gc ') 60); 6162 // the following line of code can prevent unexpected behavior caused by using an object as the session save manager, indicates that after the script is executed or exit () is called, the current session data is stored and the current session 63register_shutdown_function ('session _ write_close ') is closed; 6465session_start (); 6667 // you can use the session.
Supplement:
The session. gc_probability and session. gc_pisor configuration options in the php. ini file jointly determine the gc function call time. The default values are 1 and 1000, indicating that each request has only 1/1000 chance to call the gc function.
The above introduces the redis-based session processing method, including the content, hope to be helpful to friends interested in PHP tutorials.