php session_set_save_handler 函数的用法(mysql)(转)
- <?php
- /*============================文件说明========================================
- @filename: session.class.php
- @description: 数据库保存在线用户session,实现在线用户功能!
- @notice: session过期时间一个小时,因为我们的站点是使用cookie(有效时间是1小时)登录。
- 因此我们只记录用户登录的时间,而不是刷新一次更新一次
- 删除数据库中session记录的动作发生在用户超时后执行这个文件或正常退出(session_destory)
- @database: database:sessions field:sessionid(char32),uid(int10),last_visit(int10)
- @author: duanjianbo
- @adddate 2008-8-29 =============================================================================*/
- class session {
- private $db;
- private $lasttime=3600;//超时时间:一个小时
- function session(&$db) {
- $this->db = &$db;
- session_module_name('user'); //session文件保存方式,这个是必须的!除非在Php.ini文件中设置了
- session_set_save_handler(
- array(&$this, 'open'), //在运行session_start()时执行
- array(&$this, 'close'), //在脚本执行完成或调用session_write_close() 或 session_destroy()时被执行,即在所有session操作完后被执行
- array(&$this, 'read'), //在运行session_start()时执行,因为在session_start时,会去read当前session数据
- array(&$this, 'write'), //此方法在脚本结束和使用session_write_close()强制提交SESSION数据时执行
- array(&$this, 'destroy'), //在运行session_destroy()时执行
- array(&$this, 'gc') //执行概率由session.gc_probability 和 session.gc_divisor的值决定,时机是在open,read之后,session_start会相继执行open,read和gc
- );
- session_start(); //这也是必须的,打开session,必须在session_set_save_handler后面执行
- }
- function unserializes($data_value) {
- $vars = preg_split(
- '/([a-zA-Z_\x7f-\xff][a-zA-Z0-9_\x7f-\xff]*)\|/',
- $data_value, -1, PREG_SPLIT_NO_EMPTY |
- PREG_SPLIT_DELIM_CAPTURE
- );
- for ($i = 0; isset($vars[$i]); $i++) {
- $result[$vars[$i++]] = unserialize($vars[$i]);
- }
- return $result;
- }
- function open($path, $name) {
- return true;
- }
- function close() {
- $this->gc($this->lasttime);
- return true;
- }
- function read($SessionKey){
- $sql = "SELECT uid FROM sessions WHERE session_id = '".$SessionKey."' limit 1";
- $query =$this->db->query($sql);
- if($row=$this->db->fetch_array($query)){
- return $row['uid'];
- }else{
- return "";
- }
- }
- function write($SessionKey, $VArray) {
- require_once(MRoot.DIR_WS_CLASSES .'db_mysql_class.php');
- $db1=new DbCom();
- // make a connection to the database... now
- $db1->connect(DB_SERVER, DB_SERVER_USERNAME, DB_SERVER_PASSWORD, DB_DATABASE);
- $db1->query("set names utf8");
- $this->db=$db1;
- $SessionArray = addslashes($VArray);
- $data=$this->unserializes($VArray);
- $sql0 = "SELECT uid FROM sessions WHERE session_id = '".$SessionKey."' limit 1";
- $query0 =$this->db->query($sql0);
- if($this->db->num_rows($query0) <= 0){
- if (isset($data['webid']) && !empty($data['webid'])) {
- $this->db->query("insert into `sessions` set `session_id` = '$SessionKey',uid='".$data['webid']."',last_visit='".time()."'");
- }
- return true;
- }else{
- /*$sql = "update `sessions` set ";
- if(isset($data['webid'])){
- $sql .= "uid = '".$data['webid']."', " ;
- }
- $sql.="`last_visit` = null "
- . "where `session_id` = '$SessionKey'";
- $this->db->query($sql); */
- return true;
- }
- }
- function destroy($SessionKey) {
- $this->db->query("delete from `sessions` where `session_id` = '$SessionKey'");
- return true;
- }
- function gc($lifetime) {
- $this->db->query("delete from `sessions` where unix_timestamp(now()) -`last_visit` > '".$this->lasttime."'");
- return true;
- }
- }
- ?>
本文摘自:http://wqss.2008.blog.163.com/blog/static/912428082011823104218806/?suggestedreading
- <?php
- function _session_open($save_path,$session_name)
- {
- global $handle;
- $handle = mysql_connect('localhost','root','root') or die('数据库连接失败'); // 连接MYSQL数据库
- mysql_select_db('db_database11',$handle) or die('数据库中没有此库名'); // 找到数据库
- return(true);
- }
- function _session_close()
- {
- global $handle;
- mysql_close($handle);
- return(true);
- }
- function _session_read($key)
- {
- global $handle; // 全局变量$handle 连接数据库
- $time = time(); // 设定当前时间
- $sql = "select session_data from tb_session where session_key = '$key' and session_time > $time";
- $result = mysql_query($sql,$handle);
- $row = mysql_fetch_array($result);
- if ($row)
- {
- return($row['session_data']); // 返回Session名称及内容
- }else
- {
- return(false);
- }
- }
- function _session_write($key,$data)
- {
- global $handle;
- $time = 60*60; // 设置失效时间
- $lapse_time = time() + $time; // 得到Unix时间戳
- $sql = "select session_data from tb_session where session_key = '$key' and session_time > $lapse_time";
- $result = mysql_query($sql,$handle);
- if (mysql_num_rows($result) == 0 ) // 没有结果
- {
- $sql = "insert into tb_session values('$key','$data',$lapse_time)"; // 插入数据库sql语句
- $result = mysql_query($sql,$handle);
- }else
- {
- $sql = "update tb_session set session_key = '$key',session_data = '$data',session_time = $lapse_time where session_key = '$key'"; // 修改数据库sql语句
- $result = mysql_query($sql,$handle);
- }
- return($result);
- }
- function _session_destroy($key)
- {
- global $handle;
- $sql = "delete from tb_session where session_key = '$key'"; // 删除数据库sql语句
- $result = mysql_query($sql,$handle);
- return($result);
- }
- function _session_gc($expiry_time)
- {
- global $handle;
- $lapse_time = time(); // 将参数$expiry_time赋值为当前时间戳
- $sql = "delete from tb_session where expiry_time < $lapse_time"; // 删除数据库sql语句
- $result = mysql_query($sql,$handle);
- return($result);
- }
- session_set_save_handler('_session_open','_session_close','_session_read','_session_write','_session_destroy','_session_gc');
- session_start();
- $_SESSION['user'] = 'mr';
- $_SESSION['pwd'] = 'mrsoft';
- ?>
- session_set_save_handler
- session_set_save_handler---设置用户级 session 存储函数
- 函数原型
- void session_set_save_handler (string open, string close, string read, string write, string destroy, string gc)
- session_set_save_handler() 设置用户级 session 存储函数,用于存储和取回 session 相关的数据. 用于那些使用不同于 PHP Session 指定的存储方式的情况. 例如,在本地数据库存储 session 数据.
- 注意: 你必须设置 php.ini 里面的 session.save_handler配置参数来让 session_set_save_handler() 正常工作.
- 下面的例子提供了类似于 PHP 默认的保存文件句柄的基于文件的 session storage 方式. 这个例子可以很简单的扩展到使用熟悉的数据库引擎来进行数据库存储.
- 例子:
- 程序代码:[session_inc.php]
- <?php
- $SESS_DBHOST = "yourhost"; /* database server hostname */
- $SESS_DBNAME = "yourdb"; /* database name */
- $SESS_DBUSER = "youruser"; /* database user */
- $SESS_DBPASS = "yourpassword"; /* database password */
- $SESS_DBH = "";
- $SESS_LIFE = get_cfg_var("session.gc_maxlifetime");
- function sess_open($save_path, $session_name) {
- global $SESS_DBHOST, $SESS_DBNAME, $SESS_DBUSER, $SESS_DBPASS, $SESS_DBH;
- if (! $SESS_DBH = mysql_pconnect($SESS_DBHOST, $SESS_DBUSER, $SESS_DBPASS)) {
- echo "<li>Can't connect to $SESS_DBHOST as $SESS_DBUSER";
- echo "<li>MySQL Error: " . mysql_error();
- die;
- }
- if (! mysql_select_db($SESS_DBNAME, $SESS_DBH)) {
- echo "<li>Unable to select database $SESS_DBNAME";
- die;
- }
- return true;
- }
- function sess_close() {
- return true;
- }
- function sess_read($key) {
- global $SESS_DBH, $SESS_LIFE;
- $qry = "SELECT value FROM session_tbl WHERE sesskey = '$key' AND expiry > " . time();
- $qid = mysql_query($qry, $SESS_DBH);
- if (list($value) = mysql_fetch_row($qid)) {
- return $value;
- }
- return false;
- }
- function sess_write($key, $val) {
- global $SESS_DBH, $SESS_LIFE;
- $expiry = time() + $SESS_LIFE; //过期时间
- $value = addslashes($val);
- $qry = "INSERT INTO session_tbl VALUES ('$key', $expiry, '$value')";
- $qid = mysql_query($qry, $SESS_DBH);
- if (! $qid) {
- $qry = "UPDATE session_tbl SET expiry = $expiry, value = '$value' WHERE sesskey = '$key' AND expiry > " . time();
- $qid = mysql_query($qry, $SESS_DBH);
- }
- return $qid;
- }
- function sess_destroy($key) {
- global $SESS_DBH;
- $qry = "DELETE FROM session_tbl WHERE sesskey = '$key'";
- $qid = mysql_query($qry, $SESS_DBH);
- return $qid;
- }
- function sess_gc($maxlifetime) {
- global $SESS_DBH;
- $qry = "DELETE FROM session_tbl WHERE expiry < " . time();
- $qid = mysql_query($qry, $SESS_DBH);
- return mysql_affected_rows($SESS_DBH);
- }
- session_set_save_handler(
- "sess_open",
- "sess_close",
- "sess_read",
- "sess_write",
- "sess_destroy",
- "sess_gc");
- session_start();
- ?>
- 完成以上步骤后,在程序中使用require("session_inc.php")来代替session_start()即可,其他的session函数还是象以前一样的方法调用
利用redis解决web集群session共享的Qeephp助手类
折腾了一天,简单了实现了把session存储到redis中,依托于Qeephp。
<?php class Helper_Session{
static private $connect = FALSE; private $redis = NULL; private $redis_host; private $redis_port;
function __construct(){ $this->redis_host=Q::ini(“appini/redis_session/redis_host”); $this->redis_port=Q::ini(“appini/redis_session/redis_port”); $this->is_sso=Q::ini(“appini/redis_session/is_sso”); }
function open($sess_path = ”, $sess_name = ”) { if ( class_exists(‘redis’) ){ $redis = new Redis(); $conn = $redis->connect( $this->redis_host , $this->redis_port ); } else { throw new QException(‘服务器没有安装PHP-Redis扩展!’); } if ( $conn ){ $this->redis = $redis ; } else { throw new QException(‘无法正常连接缓存服务器!’); } return true; }
function close(){ return true; }
function read($sess_id){ return $this->redis->get(‘session:’.$sess_id); }
function write($sess_id, $data){ $sess_data=$this->redis->get(‘session:’.$sess_id); if(empty($sess_data)){ $this->redis->set(‘session:’.$sess_id,$data); } $life_time=get_cfg_var(“session.gc_maxlifetime”); $this->redis->expire(‘session:’.$sess_id,$life_time); return true; }
function destroy($sess_id){ $this->redis->delete(‘session:’.$sess_id); return true; }
function gc($sess_maxlifetime){ return true; }
function init(){ session_set_save_handler(array($this,’open’),array($this,’close’),array($this,’read’),array($this,’write’),array($this,’destroy’),array($this,’gc’)); }
} $redis_session = new Helper_Session(); $redis_session->init();
使用,先看一下qeephp的myapp.php里面。
// 导入类搜索路径 Q::import($app_config['APP_DIR']); Q::import($app_config['APP_DIR'] . ‘/model’); // 设置 session 服务 if (Q::ini(‘runtime_session_provider’)) { Q::loadClass(Q::ini(‘runtime_session_provider’)); }
// 打开 session if (Q::ini(‘runtime_session_start’)) { session_start(); // #IFDEF DEBUG QLog::log(‘session_start()’, QLog::DEBUG); QLog::log(‘session_id: ‘ . session_id(), QLog::DEBUG); // #ENDIF }
从这段代码可以知道qeephp是留有接口的,方便我们扩展,这里以helper助手类的方式体现的,放到了 app文件夹的helper里面,所以将导入类搜索路径放到了设置 session服务的上面。
在environment.yaml加入
# 设置session服务 runtime_session_provider: helper_session
在app.yaml中加入
redis_session: redis_host: 127.0.0.1 redis_port: 6379
在有redis的情况下现在就可以利用redis存储session。
需要将次方法修改
function cleanCurrentUser() { session_destroy(); //unset($_SESSION[$this->_acl_session_key]); }
由于对redis还不是太熟悉,没有实现单点登录,慢慢会完善的。
sohu技术部实习
- <?php
- /**
- * 定义 RedisSessionHandler的基础类,并完成session的初始化
- *
- * @copyright Copyright ©:2012
- * @author Tian Mo <motian@sohu-inc.com>
- * @version 2012-07-16 14:52;00
- *
- */
- // ****************************************************************************
- // This class saves the PHP session data in redis.
- // ****************************************************************************
- class RedisSessionHandler
- {
- //the redis object
- private $_redis;
- // ****************************************************************************
- // class constructor
- // ****************************************************************************
- function RedisSessionHandler ($host = '127.0.0.1', $port = 8359, $db = 15)
- {
- if(!extension_loaded('redis'))
- throw new \Exception("Redis Extension needed!");
- $_redis = new \Redis();
- //connnect to the redis
- $_redis->connect($host, $port) or die("Can't connect to the Redis!");
- $_redis->auth("TechIpd.Sohu");
- $this->_redis = $_redis;
- //select the db
- $this->_redis->select($db);
- } // php_Session
- function open ($save_path, $session_name)
- // open the session.
- {
- // do nothing
- return TRUE;
- } // open
- function close ()
- // close the session.
- {
- return $this->gc();
- } // close
- function read ($session_id)
- // read any data for this session.
- {
- return $this->_redis->get($session_id);
- } // read
- function write ($session_id, $session_data)
- // write session data to redis.
- {
- $this->_redis->setnx($session_id, $session_data);
- //Be careful,we must be the life time all right.
- $this->_redis->expire($session_id, /*get_cfg_var("session.gc_maxlifetime")*/3600 * 24);
- return TRUE;
- } // write
- function destroy ($session_id)
- // destroy the specified session.
- {
- $this->_redis->delete($session_id);
- return TRUE;
- } // destroy
- function gc ()
- // perform garbage collection.
- {
- return TRUE;
- } // gc
- function __destruct ()
- // ensure session data is written out before classes are destroyed
- // (see http://bugs.php.net/bug.php?id=33772 for details)
- {
- @session_write_close();
- } // __destruct
- //redis session start
- function init(&$sessionObject)
- {
- //set in my handler
- ini_set('session.save_handler', 'user');
- session_set_save_handler(array(&$sessionObject, 'open'),
- array(&$sessionObject, 'close'),
- array(&$sessionObject, 'read'),
- array(&$sessionObject, 'write'),
- array(&$sessionObject, 'destroy'),
- array(&$sessionObject, 'gc'));
- // the following prevents unexpected effects when using objects as save handlers
- register_shutdown_function('session_write_close');
- // proceed to set and retrieve values by key from $_SESSION
- session_start();
- }
- }
- //@test redis
- #$session_class = new RedisSessionHandler();
- #$session_class->init($session_class);
- #$_SESSION['nn'] = 'successful';
- ?>
/**
* 定义 RedisSessionHandler的基础类,并完成session的初始化
*
* @copyright Copyright ©:2012
* @author Tian Mo <motian@sohu-inc.com>
* @version 2012-07-16 14:52;00
*
*/
// ****************************************************************************
// This class saves the PHP session data in redis.
// ****************************************************************************
class RedisSessionHandler
{
//the redis object
private $_redis;
// ****************************************************************************
// class constructor
// ****************************************************************************
function RedisSessionHandler ($host = '127.0.0.1', $port = 8359, $db = 15)
{
if(!extension_loaded('redis'))
throw new \Exception("Redis Extension needed!");
$_redis = new \Redis();
//connnect to the redis
$_redis->connect($host, $port) or die("Can't connect to the Redis!");
$_redis->auth("TechIpd.Sohu");
$this->_redis = $_redis;
//select the db
$this->_redis->select($db);
} // php_Session
function open ($save_path, $session_name)
// open the session.
{
// do nothing
return TRUE;
} // open
function close ()
// close the session.
{
return $this->gc();
} // close
function read ($session_id)
// read any data for this session.
{
return $this->_redis->get($session_id);
} // read
function write ($session_id, $session_data)
// write session data to redis.
{
$this->_redis->setnx($session_id, $session_data);
//Be careful,we must be the life time all right.
$this->_redis->expire($session_id, /*get_cfg_var("session.gc_maxlifetime")*/3600 * 24);
return TRUE;
} // write
function destroy ($session_id)
// destroy the specified session.
{
$this->_redis->delete($session_id);
return TRUE;
} // destroy
function gc ()
// perform garbage collection.
{
return TRUE;
} // gc
function __destruct ()
// ensure session data is written out before classes are destroyed
// (see http://bugs.php.net/bug.php?id=33772 for details)
{
@session_write_close();
} // __destruct
//redis session start
function init(&$sessionObject)
{
//set in my handler
ini_set('session.save_handler', 'user');
session_set_save_handler(array(&$sessionObject, 'open'),
array(&$sessionObject, 'close'),
array(&$sessionObject, 'read'),
array(&$sessionObject, 'write'),
array(&$sessionObject, 'destroy'),
array(&$sessionObject, 'gc'));
// the following prevents unexpected effects when using objects as save handlers
register_shutdown_function('session_write_close');
// proceed to set and retrieve values by key from $_SESSION
session_start();
}
}
//@test redis
#$session_class = new RedisSessionHandler();
#$session_class->init($session_class);
#$_SESSION['nn'] = 'successful';
?>