session_set_save_handler()函数的实例

<?php
/**
CREATE TABLE IF NOT EXISTS `sessions` (
  `session` varchar(255) character set utf8 collate utf8_bin NOT NULL,
  `session_expires` int(10) unsigned NOT NULL default '0',
  `session_data` text collate utf8_unicode_ci,
  PRIMARY KEY  (`session`)
) ENGINE=MyISAM DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;
*/
class Session {
    /**
     * a database connection resource
     * @var resource
     */
    private static $_sess_db;

    /**
     * Open the session
     * @return bool
     */
    public static function open() {
       
        if (self::$_sess_db = mysql_connect('localhost', 'root', '')) {
            return mysql_select_db('my_application', self::$_sess_db);
        }
        return false;
    }

    /**
     * Close the session
     * @return bool
     */
    public static function close() {
        return mysql_close(self::$_sess_db);
    }

    /**
     * Read the session
     * @param int session id
     * @return string string of the sessoin
     */
    public static function read($id) {
        $id = mysql_real_escape_string($id);
        $sql = sprintf("SELECT `session_data` FROM `sessions` WHERE `session` = '%s'", $id);
        if ($result = mysql_query($sql, self::$_sess_db)) {
            if (mysql_num_rows($result)) {
                $record = mysql_fetch_assoc($result);
                return $record['session_data'];
            }
        }
        return '';
    }

    /**
     * Write the session
     * @param int session id
     * @param string data of the session
     */
    public static function write($id, $data) {
        $sql = sprintf("REPLACE INTO `sessions` VALUES('%s', '%s', '%s')",
                       mysql_real_escape_string($id),
                       mysql_real_escape_string(time()),
                       mysql_real_escape_string($data)
                       );
        return mysql_query($sql, self::$_sess_db);
    }

    /**
     * Destoroy the session
     * @param int session id
     * @return bool
     */
    public static function destroy($id) {
        $sql = sprintf("DELETE FROM `sessions` WHERE `session` = '%s'", $id);
        return mysql_query($sql, self::$_sess_db);
    }

    /**
     * Garbage Collector
     * @param int life time (sec.)
     * @return bool
     * @see session.gc_divisor      100
     * @see session.gc_maxlifetime 1440
     * @see session.gc_probability    1
     * @usage execution rate 1/100
     *        (session.gc_probability/session.gc_divisor)
     */
    public static function gc($max) {
        $sql = sprintf("DELETE FROM `sessions` WHERE `session_expires` < '%s'",
                       mysql_real_escape_string(time() - $max));
        return mysql_query($sql, self::$_sess_db);
    }
}

//ini_set('session.gc_probability', 50);
ini_set('session.save_handler', 'user');

session_set_save_handler(array('Session', 'open'),
                         array('Session', 'close'),
                         array('Session', 'read'),
                         array('Session', 'write'),
                         array('Session', 'destroy'),
                         array('Session', 'gc')
                         );

if (session_id() == "") session_start();
//session_regenerate_id(false); //also works fine
if (isset($_SESSION['counter'])) {
    $_SESSION['counter']++;
} else {
    $_SESSION['counter'] = 1;
}
echo '<br/>SessionID: '. session_id() .'<br/>Counter: '. $_SESSION['counter'];



//第二个版本
/*
CREATE TABLE `ws_sessions` (
  `session_id` varchar(255) binary NOT NULL default '',
  `session_expires` int(10) unsigned NOT NULL default '0',
  `session_data` text,
  PRIMARY KEY  (`session_id`)
) TYPE=InnoDB;
*/

class session {
   // session-lifetime
   var $lifeTime;
   // mysql-handle
   var $dbHandle;
   function open($savePath, $sessName) {
       // get session-lifetime
       $this->lifeTime = get_cfg_var("session.gc_maxlifetime");
       // open database-connection
       $dbHandle = @mysql_connect("server","user","password");
       $dbSel = @mysql_select_db("database",$dbHandle);
       // return success
       if(!$dbHandle || !$dbSel)
           return false;
       $this->dbHandle = $dbHandle;
       return true;
   }
   function close() {
       $this->gc(ini_get('session.gc_maxlifetime'));
       // close database-connection
       return @mysql_close($this->dbHandle);
   }
   function read($sessID) {
       // fetch session-data
       $res = mysql_query("SELECT session_data AS d FROM ws_sessions
                           WHERE session_id = '$sessID'
                           AND session_expires > ".time(),$this->dbHandle);
       // return data or an empty string at failure
       if($row = mysql_fetch_assoc($res))
           return $row['d'];
       return "";
   }
   function write($sessID,$sessData) {
       // new session-expire-time
       $newExp = time() + $this->lifeTime;
       // is a session with this id in the database?
       $res = mysql_query("SELECT * FROM ws_sessions
                           WHERE session_id = '$sessID'",$this->dbHandle);
       // if yes,
       if(mysql_num_rows($res)) {
           // ...update session-data
           mysql_query("UPDATE ws_sessions
                         SET session_expires = '$newExp',
                         session_data = '$sessData'
                         WHERE session_id = '$sessID'",$this->dbHandle);
           // if something happened, return true
           if(mysql_affected_rows($this->dbHandle))
               return true;
       }
       // if no session-data was found,
       else {
           // create a new row
           mysql_query("INSERT INTO ws_sessions (
                         session_id,
                         session_expires,
                         session_data)
                         VALUES(
                         '$sessID',
                         '$newExp',
                         '$sessData')",$this->dbHandle);
           // if row was created, return true
           if(mysql_affected_rows($this->dbHandle))
               return true;
       }
       // an unknown error occured
       return false;
   }
   function destroy($sessID) {
       // delete session-data
       mysql_query("DELETE FROM ws_sessions WHERE session_id = '$sessID'",$this->dbHandle);
       // if session was deleted, return true,
       if(mysql_affected_rows($this->dbHandle))
           return true;
       // ...else return false
       return false;
   }
   function gc($sessMaxLifeTime) {
       // delete old sessions
       mysql_query("DELETE FROM ws_sessions WHERE session_expires < ".time(),$this->dbHandle);
       // return affected rows
       return mysql_affected_rows($this->dbHandle);
   }
}
$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();


//第三个版本:
$DB_SERVER = "server"; /* database server hostname */
$DB_NAME = "dbname"; /* database name */
$DB_USER = "root"; /* database user */
$DB_PASS = "*************"; /* database password */
    
$DB_SELECT_DB = "";
$SESS_LIFE = get_cfg_var("session.gc_maxlifetime");
    
    function sess_open($save_path, $session_name){
        global $DB_SERVER, $DB_NAME, $DB_USER, $DB_PASS, $DB_SELECT_DB;

        if (! $DB_SELECT_DB = mysql_pconnect($DB_SERVER, $DB_USER, $DB_PASS)) {
           echo "SORRY! MYSQL ERROR : Can't connect to $DB_SERVER as $DB_USER";
           echo "MySQL Error: ", mysql_error();
           die;
        }

        if (! mysql_select_db($DB_NAME, $DB_SELECT_DB)) {
           echo "SORRY! MYSQL ERROR : Unable to select database $DB_NAME";
           die;
        }
           return true;
    }
  
    function sess_close() {
       return true;
    }
  
    function sess_read($SessionKey){
        global $DB_SELECT_DB, $SESS_LIFE;   
        $Query = "SELECT SessionArray FROM cdb_global_sessions WHERE SessionKey = '".$SessionKey."' AND SessionExpTime > " . time();
        $Result = mysql_query($Query, $DB_SELECT_DB);

        if (list($SessionArray) = mysql_fetch_row($Result)) {
             return $SessionArray;
        }

        return false;
    }
  
    function sess_write($SessionKey, $VArray) {
        global $DB_SELECT_DB, $SESS_LIFE;

        $SessionExpTime = time() + $SESS_LIFE;
        $SessionArray = addslashes($VArray);

        $Query = "INSERT INTO cdb_global_sessions (SessionKey,SessionExpTime,SessionArray) VALUES ('".$SessionKey."','".$SessionExpTime."','".$SessionArray."')";
        $Result = mysql_query($Query, $DB_SELECT_DB);

        if (!$Result){
             $Query = "UPDATE cdb_global_sessions SET SessionExpTime = '".$SessionExpTime."', SessionArray = '".$SessionArray."' WHERE SessionKey = '".$SessionKey."' AND SessionExpTime > " . time();
             $Result = mysql_query($Query, $DB_SELECT_DB);
        }   
        return $Result;
    }
  
    function sess_destroy($SessionKey) {
        global $DB_SELECT_DB;

        $Query = "DELETE FROM cdb_global_sessions WHERE SessionKey = '".$SessionKey."'";
        $Result = mysql_query($Query, $DB_SELECT_DB);

        return $Result;
    }
  
    function sess_gc($maxlifetime) {
        global $DB_SELECT_DB;

        $Query = "DELETE FROM cdb_global_sessions WHERE SessionExpTime < " . time();
        $Result = mysql_query($Query, $DB_SELECT_DB);

        return mysql_affected_rows($DB_SELECT_DB);
    }
  
    session_set_save_handler(
                "sess_open",
                "sess_close",
                "sess_read",
                "sess_write",
                "sess_destroy",
                "sess_gc");
    session_start();

session_set_save_handler( 
                  "sess_open",   /*   session_start()调用   */ 
                  "sess_close",   /*   程序结束时调用   */ 
                  "sess_read",   /*   session_start()调用   */ 
                  "sess_write",   /*   程序结束时调用   */ 
                  "sess_destroy",   /*   session_destroy()调用   */ 
                  "sess_gc"   /*   操作系统gc进程调用   */ 
  ); 
//通知php使用自定义的session处理函数来操作session,而不使用php预置的方法
?>

你可能感兴趣的:(mysql,session,function,database,delete,query)