利用Redis存储Session值的类

【原创】利用Redis存储Session值的类

/**
 * @name session in redis
 * @uses store session
 * @author  jiang kejun <jinhua_k9@163.com>
 * @since  2013.08.20
 * @version $Id: code.php 246 2013.08.20 create jkj $
 * @example  :
 * # $config = array();
   # $config['mode']=1;  
   # $redis = new SessionInRedis($config);
 */
class SessionInRedis
{
	// variable group
	private $_handle = null;
	private $_lifttime = 912;  // birth
	private $_session = null;
	private $_config = array();
	private $_cookie = null;
	/**
	 * SessionInRedis
	 *
	 * @param array $config
	 * @return this
	 */
	function __construct($config){
		if(!isset($config['host']) || empty($config['host'])){
			$config['host'] = '127.0.0.1';
		}
		if(!isset($config['port']) || empty($config['port'])){
			$config['port'] = 6379;
		}
		// mode can write from here
		// $config[mode] =1 or 2 or 3
		
		$this->_config = $config;
		// =,; \t\r\n\013\014
		$this->_cookie = "REDIS_SESSID";
		$this->_initRedis();
		$this->_initSession();
		
		return $this;
	}
	/**
	 * Create a redis, connecting
	 *
	 * @return object|null
	 */
	private function _initRedis(){
		if(!extension_loaded("Redis")){
			throw new Exception("You must install the library for redis");
		}
		if($this->_handle == null){
			extract($this->_config);
			try{
				$this->_handle = new Redis();
				$this->_handle->connect($host, $port, 10);
			}catch(RedisException $r){
				printf("The redis-server is not open or unable to connect [%s:%s]! 
				line:[%s]", $host, $port, __LINE__ );
				exit();
			}
		}
		return $this->_handle;
	}
	/**
	 * session-handle-initialize
	 * @access private 
	 * 
	 * @return bool
	 */
	private function _initSession(){
		$count = 0;
		if($_COOKIE[$this->_cookie]){
			if($this->exists($_COOKIE[$this->_cookie])){
				$this->_session = addslashes($_COOKIE[$this->_cookie]);
				$count++;
			}
		}
		if($count==0){
			$now = time();
			$this->_session = md5(uniqid());
			/*
			header('P3P: CP="CURa ADMa DEVa PSAo PSDo OUR BUS UNI PUR INT DEM STA 
				PRECOM NAV OTC NOI DSP COR"');
			*/
			setcookie($this->_cookie, $this->_session, $now + $this->_lifttime, "/");
		}
		//$this->_lifttime = @ini_get('session.gc_maxlifetime');
		// is it necessary to?
		session_module_name("redis");  // redis,files,user
		session_set_save_handler(
						array(&$this, "open"), 
                        array(&$this, "close"), 
                        array(&$this, "read"), 
                        array(&$this, "write"), 
                        array(&$this, "destroy"), 
                        array(&$this, "gc"));
        //session_start();
		return true;
	}
	//---------------------------------------//
	/**
	 * redissession-open
	 * 
	 * @return bool
	 */
	function open(){
		if(!$this->_handle instanceof Redis){
			throw new Exception("Illegal instance");
		}
		if(!$this->ping(7)){
			
		}
		return true;
	}
	/**
	 * redissession-close
	 *
	 * @return bool
	 */
	function close(){
		$this->_handle->close();
		return true;
	}
	/**
	 * redissession-get
	 *
	 * @param string|array $sessID
	 * @return mixed
	 */
	function read($sessID){
		if(!$this->exists($this->_session)) {return false;}
		if(is_array($sessID)){
			return $this->_handle->hMGet($this->_session, $sessID);
		}
		return $this->_handle->hGet($this->_session, $sessID);
	}
	/**
	 * redissession-set
	 *
	 * @param string|array $sessID
	 * @param mixed $sessData
	 * @return bool
	 */
	function write($sessID, $sessData){
		$now = time();
		if(is_array($sessID) && is_array($sessData)){
			$data = array_combine($sessID, $sessData);
			$this->_handle->hMSet($this->_session, $data);
		}else{
			$this->_handle->hSet($this->_session, $sessID, $sessData);
		}
		// Has Its Limitation
		$this->_handle->expireAt($this->_session, $now + $this->_lifttime);
		return true;
	}
	/**
	 * redissession-destroy
	 *
	 * @param string $sessID
	 * @return bool
	 */
	function destroy($sessID) { 
        $this->_handle->hDel($this->_session, $sessID);
		return true;
    }
    /**
     * redissession-gc (autoclear)
     *
     * @return bool
     */
    function gc() {
    	// is overdued
    	//return $this->_handle->ttl($this->_session);
    	return true;
    }
    //---------------------------------------//
    
    /**
     * Returns the keys in a hash, as an array of strings.
     *
     * @return array
     */
    function getHashKeysByCurrSid(){
    	return $this->_handle->hKeys($this->_session);
    }
    
    /**
     * Returns the keys that match a certain pattern.
     *
     * @param string $key
     * @return array
     */
    function keys($key='*'){
    	return $this->_handle->keys($key);
    }
    
    /**
     * Verify if the specified key exists.
     *
     * @param string $key
     * @return bool
     */
    function exists($key){
    	return $this->_handle->exists($key);
    }
    
    /**
     * Returns the whole hash, as an array of strings indexed by strings.
     *
     * @return array
     */
    function getAll(){
    	return $this->_handle->hGetAll($this->_session);
    }
    
    /**
     * Check the current connection status
     *
     * @param int $ttl
     * @return bool
     */
    function ping($ttl=10){
    	set_time_limit($ttl);
    	try{
    		$status = $this->_handle->ping();
    		if($status == "+PONG"){
    			return true;
    		}
    	}catch(RedisException $r){
    		printf("the current connection status:[blocking]! line:%s", 
    			__LINE__);
    		exit();
    	}
    }
    
    /**
     * delete a session
     *
     * @param string $sess
     * @return int
     */
    function del($sess){
    	return $this->_handle->delete($sess);
    }
}


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值