<?php
/**
* session使用memcached Aboc QQ:9986584
*/
class Session{
//过期时间
private $_LEFT_TIME = 3600;
//当前时间
private $_nowtime = 0;
//过期的确切时间
private $_expiry = 0;
private $_sessionid = '';
private $_memcached_host = MEMCACHEDHOST;
private $_memcached_port = MEMCACHEDPORT;
public $mem;
public function open() {
$this->_nowtime = time();
$this->_expiry = $this->_nowtime+$this->_LEFT_TIME;
if (isset($_COOKIE['PHPSESSID'])){
$this->_sessionid = $_COOKIE['PHPSESSID'];
//session_id($this->_sessionid);
$this->write_sessionid($this->_sessionid);
} else {
/**
* 要弄一个唯一的值才可以
*/
$tempsessionid = md5($_SERVER['REMOTE_ADDR'].$this->getIp().$_SERVER['HTTP_USER_AGENT'].rand(100000,999999));
$this->write_sessionid($tempsessionid);
$this->_sessionid = $tempsessionid;
session_id($this->_sessionid);
}
$this->mem = new Memcache;
$this->mem->connect($this->_memcached_host,$this->_memcached_port);
}
/**
* 设置过期时间,秒
* Enter description here ...
* @param unknown_type $seconds
*/
public function setLefttime($seconds=3600){
$this->_LEFT_TIME = $seconds;
}
private function getIp() {
if (isset ( $_SERVER )) {
if (isset ( $_SERVER ["HTTP_X_FORWARDED_FOR"] )) {
$realip = $_SERVER ["HTTP_X_FORWARDED_FOR"];
} else if (isset ( $_SERVER ["HTTP_CLIENT_IP"] )) {
$realip = $_SERVER ["HTTP_CLIENT_IP"];
} else {
$realip = $_SERVER ["REMOTE_ADDR"];
}
} else {
if (getenv ( "HTTP_X_FORWARDED_FOR" )) {
$realip = getenv ( "HTTP_X_FORWARDED_FOR" );
} else if (getenv ( "HTTP_CLIENT_IP" )) {
$realip = getenv ( "HTTP_CLIENT_IP" );
} else {
$realip = getenv ( "REMOTE_ADDR" );
}
}
if(isset($realip[16]))$realip = substr($realip,0,15);
return $realip;
}
/**
* 将自定义的sessionid写入cookie
*
* @param unknown_type $sessionid
*/
private function write_sessionid($sessionid){
setcookie('PHPSESSID',$sessionid,$this->_expiry,'/');
}
public function close(){
}
/**
* 读
*/
public function read() {
//echo $this->_sessionid;
$content =$this->mem->get($this->_sessionid);
if ($content){
return $content;
}else{
$this->mem->set($this->_sessionid,'',0,$this->_LEFT_TIME);
return false;
}
}
/**
* 写
*/
public function write( $sessionid , $sessdata ) {
$this->mem->replace($this->_sessionid,$sessdata,0,$this->_LEFT_TIME);
return true;
}
/**
* 指定销毁
*/
public function destroy() {
$this->mem->delete($this->_sessionid);
}
/**
* 销毁过期的数据
*/
public function gc() {
//
}
public function __destruct(){
//$this->gc();
}
}
$session = new Session();
session_set_save_handler(
array(&$session,'open'),
array(&$session,'close'),
array(&$session,'read'),
array(&$session,'write'),
array(&$session,'destroy'),
array(&$session,'gc')
);
session_start();
?>