/**
* 文件描述 Session类
* =================================================================
* 文件名称 session.class.php
* -----------------------------------------------------------------
* 适用环境: PHP5.2.x / mysql 5.0.x
* -----------------------------------------------------------------
* 作 者 04ie。com
* -----------------------------------------------------------------
* 创建时间 2010-2-1
* =================================================================
*/
class Session
{
/**
* session默认有效时间
* @access public
* @var ineger $_expiry
*/
public $_expiry = 3600;
/**
* 有效域名
* @access public
* @var string $_domain
*/
public $_domain = '.phpfamily.cn';
//初始化
public function __construct()
{
ini_set('session.use_trans_id', 0);
ini_set('session.gc_maxlifetime', $this->_expiry);
ini_set('session.use_cookie', 1);
ini_set('session.cookie_path', '/');
ini_set('session.cookie_domain', $this->_domain);
session_module_name('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();
}
/**
* 打开session
* @access public
* @param string $savePath
* @param string $sName
* @return true
*/
public function open($savePath, $sName)
{
$this->_conn = mysql_connect('localhost', 'root', '');
mysql_select_db('databases');
mysql_query('SET NAMES "utf8"');
return true;
}
/**
* 关闭session
* @access public
* @return bool
*/
public function close()
{
return mysql_close($this->_conn);
}
/**
* 读取session
* @access public
* @param string $sid sessionID
* @return mixed
*/
public function read($sid)
{
$sql = "SELECT data FROM sessions WHERE sessionid='%s'";
$sql = sprintf($sql, $sid);
$res = mysql_query($sql, $this->_conn);
$row = mysql_fetch_assoc($res);
return !$row ? null : $row['data'];
}
/**
* 写入session
* @access public
* @param string $sid sessionID
* @param string $data serialize序列化后的session内容
* @return
*/
public function write($sid, $data)
{
$expiry = time() + $this->_expiry;
$sql = "REPLACE INTO sessions (sessionid,expiratio
n,data) VALUES ('%s', '%d', '%s')";
$sql = sprintf($sql, $sid, $expiry, $data);
mysql_query($sql, $this->_conn);
return true;
}
/**
* 销毁session
* @access public
* @param string $sid sessionID
* @return
*/
public function destroy($sid)
{
$sql = "DELETE FROM sessions WHERE sessionid='%s'";
$sql = sprintf($sql, $sid);
mysql_query($sql, $this->_conn);
return true;
}
/**
* 清理过期session
* @access public
* @param integer $time
* @return
*/
public function gc($time = 0)
{
$sql = "DELETE FROM sessions WHERE expiration < '%d'";
$sql = sprintf($sql, time());
mysql_query($sql, $this->_conn);
mysql_query('OPTIMIZE TABLE sessions');
return true;
}
|