123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111 |
- <?php
- /**
- * Created by PhpStorm.
- * User: stanley-king
- * Date: 16/1/30
- * Time: 下午3:43
- */
- class session
- {
- static $stInstance = NULL;
- private $fdestroy = false;
- private $redis = NULL;
- private $enable = false;
- const type = 'redis';
- const save_path = 'tcp://127.0.0.1:6379';
- const prefix = 'PHPREDIS_SESSION';
- static public function instance()
- {
- if(self::$stInstance == NULL) {
- self::$stInstance = new session();
- }
- return self::$stInstance;
- }
- private function __construct()
- {
- $this->redis = new Redis;
- $this->enable = $this->redis->connect('127.0.0.1', 6379);
- }
- public function init()
- {
- @ini_set("session.save_handler", "redis");
- session_save_path(self::save_path);
- session_set_save_handler(
- array(&$this,'onOpen'),
- array(&$this,'onClose'),
- array(&$this,'onRead'),
- array(&$this,'onWrite'),
- array(&$this,'onDestroy'),
- array(&$this,'onGc'),
- array(&$this,'onCreateSid'));
- }
- public function start()
- {
- //会触发,open 和 read 函数
- session_start();
- }
- public function end()
- {
- // 会触发write 和 close 函数
- if($this->fdestroy == false) {
- session_write_close();
- }
- foreach($_SESSION as $key=>$value)
- {
- unset($_SESSION[$key]);
- }
- }
- public function destroy() {
- $this->fdestroy = true;
- session_destroy();//会触发destroy 和 close 函数
- }
- public function onOpen() {
- return true;
- }
- public function onRead($sid)
- {
- $ret = $this->redis->hGet(self::prefix,$sid);
- if(empty($ret)) {
- return '';
- } else {
- fcgi_header("Set-Cookie: PHPSESSID={$sid}");
- return $ret[0];
- }
- }
- public function onClose() {
- return true;
- }
- public function onWrite($sid, $data) {
- return $this->redis->hSet(self::prefix,$sid,$data);
- }
- public function onDestroy($sid) {
- return dcache($sid,self::prefix);
- }
- public function onGc($expire) {
- return true;
- }
- // public function onCreateSid()
- // {
- // $sid = 'vnk730je4l1c20cc479gpoesm6';
- //
- // return $sid;
- // }
- }
|