- <?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';
?>
