config = array( 'host'=>$host, 'port'=>$port ); $this->redis = new Redis(); $this->redis->connect($this->config['host'],$this->config['port']); //设置当前的sessionid生成的命名空间 $this->namespace = $namespace; //设置初始化的session_id $session_name = ini_get("session.name"); //没有设置过session,新的会话,需要重新生成sessionid if ( empty($_COOKIE[$session_name]) ) { $this->session_id = true; } } public function open($savePath, $sessionName){ $connect = $this->redis->connect($this->config['host'],$this->config['port']); if(!$connect) return false; //在初次设置的时候,重设PHP本身的session_id并判断session_id是否已经存在 $id = session_id(); if($this->session_id && $this->session_id != $id){ do{ $this->session_id = $this->session_id(); }while($this->redis->exists($this->namespace.'@'.$this->session_id)); session_id($this->session_id); } //设置生成周期 $this->maxlifetime = ini_get("session.gc_maxlifetime"); return true; } public function close(){ $this->redis->close(); return true; } public function read($id){ return $this->redis->get($this->namespace.'@'.$id); } public function write($id, $data){ return $this->redis->setex($this->namespace.'@'.$id,$this->maxlifetime,$data); } public function destroy($id){ $this->redis->delete($this->namespace.'@'.$id); return true; } public function gc($maxlifetime){ return true; } /** * 生成guid */ private function session_id(){ $uid = uniqid("", true); $data = $this->namespace; $data .= $_SERVER['REQUEST_TIME']; $data .= $_SERVER['HTTP_USER_AGENT']; $data .= $_SERVER['SERVER_ADDR']; $data .= $_SERVER['SERVER_PORT']; $data .= $_SERVER['REMOTE_ADDR']; $data .= $_SERVER['REMOTE_PORT']; $hash = strtoupper(hash('ripemd128', $uid . md5($data))); return substr($hash,0,32); } } $param = array( "namespace"=>'', "redis_host"=>'127.0.0.1', "redis_port"=>'6379' ); if($param){ $handler = new RedisSessionHandler($param['namespace'],$param['redis_host'],$param['redis_port']); session_set_save_handler($handler, true); }