<?php
/**
* 缓存库
*
* @package libs
* @category API
* @author 周阳<305846826@qq.com>
* @copyright 街网科技
* @version 2.0
* @link http://www.jieone.com
*/
class DBMemcache{
const SERVER_CODE = 1;
/**
* 服务器IP
* @var unknown
*/
const SERVER_IP="127.0.0.1";
/**
* 服务器端口
* @var unknown
*/
const SERVER_PORT=11211;
/**
* 设置Session数据
* @param string $key
* @param string $value
*/
public function setSession($key, $value){
$memcache = new Memcache;
$memcache->connect(self::SERVER_IP, self::SERVER_PORT);
$memcache->delete($key);
$ret = $memcache->set($key, $value, MEMCACHE_COMPRESSED);
$memcache->close();
return $ret;
}
/**
* 删除Sesson数据
* @param string $key
*/
private function deleteSession($key){
$memcache = new Memcache;
$memcache->connect(self::SERVER_IP, self::SERVER_PORT);
$memcache->delete($key);
$memcache->close();
}
/**
* 得到Session数据
* @param string $key
*/
public function getSession($key){
$memcache = new Memcache;
$memcache->connect(self::SERVER_IP, self::SERVER_PORT);
$data = $memcache->get($key);
$memcache->close();
return $data;
}
/**
* 保存用户登录SID
* 保存sessionVal 是为了防止重新登录
* @param int $userid 用户ID
* @param int $type 分类
*/
public static function saveSid($userid,$type){
$time=time();
$sessionid = md5($type . $userid .$time);
$sessionval = md5($type . $time . $userid);
//删除原来的信息
$val=self::getSession($userid.$type);
if(!empty($val)&&isset($val["sessionid"])){
self::deleteSession($val["sessionid"]);
}
self::setSession($sessionid, array('userid' => $userid, 'type' => $type, 'sessionval' => $sessionval,'time' => $time));
self::setSession($userid.$type, array("sessionval"=>$sessionval,"sessionid"=>$sessionid));
return $sessionid;
}
/**
* 删除SID
* @param string $sessionid
*/
public static function deleteSid($sessionid){
$key = self::getSession($sessionid);
if(empty($key)){
return false;
}
if (isset($key["sessionval"])) {
self::deleteSession($key["sessionval"]);
}
self::deleteSession($sessionid);
}
/**
* 得到用户ID
*/
public static function getUserID($sessionid){
$sessionid = trim($sessionid);
if(!$sessionid){
return 0;
}
$key = self::getSession($sessionid);
if (empty($key)) {
return 0;
}
if(!isset($key["userid"])||!isset($key["type"])){
return 0;
}
$type=$key['type'];
$userid=$key['userid'];
$val=self::getSession($userid.$type);
if(!isset($val["sessionval"])||!isset($val["sessionid"])){
return 0;
}
if($val["sessionval"]!=$key['sessionval']) {
return 0;
}
return $userid;
}
}
DBMemcache,这个我喜欢
最新推荐文章于 2016-03-24 10:08:44 发布