The example in this article describes the implementation method of ThinkPHP custom Redis processing SESSION. Share it with everyone for your reference, the details are as follows:
In daily life, we use session to save user login information. Commonly used session saving methods include: file saving (default), database saving, Redis saving, memcached, etc. Here we mainly record the usage of using Redis to save the session when using ThinkPHP to process the session.
1. Define in the configuration item:
'SESSION_TYPE' => 'Redis', //session保存类型 'SESSION_PREFIX' => 'sess_', //session前缀 'REDIS_HOST' => '127.0.0.1' //REDIS服务器地址 'REDIS_PORT' => 6379, //REDIS连接端口号 'SESSION_EXPIRE' => 3600, //SESSION过期时间
You can find the method of defining session in the ThinkPHP/Common/functions.php file, and read the judgment of the session driver at around line 1179. If we define the configuration item SESSION_TYPE, a new Redis object will be created and the session storage function session_set_save_handler() will be called.
2. Create a new Redis.class.php file in the ThinkPHPLibraryThinkSessionDriver directory
The content of the file is as follows:
<?php namespace Think\Session\Driver; class Redis { // Redis连接对象 private $redis; // Session过期时间 private $expire; /** * 打开方法 * @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')); } /** * 关闭 * @return type */ public function close() { return $this->redis->close(); } /** * 读取 * @param string $id * @return type */ public function read($id) { $id = C('SESSION_PREFIX') . $id; $data = $this->redis->get($id); return $data ? $data : ''; } /** * 写入 * @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); } /** * 销毁 * @param string $id */ public function destroy($id) { $id = C('SESSION_PREFIX') . $id; $this->redis->delete($id); } /** * 垃圾回收 * @param type $maxLifeTime * @return boolean */ public function gc($maxLifeTime) { return true; } }
This completes the session processing by Redis.
The method of memcached is almost the same as Redis!
I hope this article will help you design PHP programs based on the ThinkPHP framework.
For more articles related to ThinkPHP’s custom Redis processing SESSION implementation method, please pay attention to the PHP Chinese website!