redis 替代php文件存储session的实例
redis 替代php文件存储session的实例
查看实例之前请先了解 PHP session_set_save_handler函数的用法
定义个SessionManager 类
class SessionManager { private $redis; public function __construct(){ $this->redis = new Redis(); $this->redis->connect('192.168.0.102', 6379); $retval =session_set_save_handler( array($this,"open"), array($this,"close"), array($this,"read"), array($this,"write"), array($this,"destroy"), array($this,"gc") ); session_start(); } public function open($path,$name){ return true; } public function close(){ return true; } public function read($id){ $session_value = $this->redis->get($id); if($session_value){ return $session_value; }else{ return ""; } } public function write($id,$data){ if($this->redis->set($id,$data)){ return true; }else{ return false; } } public function destroy($id){ if($this->redis->delete($id)){ return true; }else{ return false; } } public function gc($maxlifetime){ return true; } public function __destruct(){ session_write_close(); } }
创建一个session_set.php 代码如下
include("SessionManager.php"); new SessionManager(); $_SESSION['user_name']="[email protected]";
创建一个session_set.php 代码如下
include("SessionManager.php"); new SessionManager(); echo $_SESSION['user_name'];
测试输出 结果 [email protected]
注意 :php.ini session.save-hadler 设置为 user ,否则session_set_save_handler 不会生效
如有疑问请留言或者到本站社区交流讨论,感谢阅读,希望能帮助到大家,谢谢大家对本站的支持!
相关推荐
houmenghu 2020-11-17
我心似明月 2020-11-09
oraclemch 2020-11-06
ltd00 2020-09-12
康慧欣 2020-09-10
waveclouds 2020-09-04
蓝色深海 2020-09-15
jincheng 2020-09-01
思君夜未眠 2020-08-25
取个好名字真难 2020-08-06
歆萌 2020-08-03
阳光之吻 2020-08-03
婷婷小屋 2020-07-28
solarspot 2020-07-28
MLXY 2020-07-26
dxbjfu0 2020-07-26
songbinxu 2020-07-19
83520298 2020-07-06