EcShop 中Session 处理解读与参考

  <?php 
if (!defined('IN_ECS')) { 
    die('Hacking attempt'); 
} 
class cls_session { 
    var $db = NULL; # 数据库连接 
    var $session_table = ''; # Session 表 
    var $max_life_time = 144000; # SESSION 生存时间 
    var $session_name = ''; # Session 名称 
    var $session_id = ''; # Session ID 
    var $session_expiry = ''; # Session 过期时间 
    var $session_md5 = ''; # Session md5值 
    var $session_cookie_path = '/'; # Session 保存的 Cookie 路径 
    var $session_cookie_domain = ''; # Session 保存的 Cookie 域名 
    var $session_cookie_secure = false; # Session 保存的 Cookie 安全域 
    var $_ip = ''; # IP地址 
    var $_time = 0; # 当前时间 
    # PHP5的构造函数,用于创建一个SESSION对象,为了保证对PHP4的兼容
    function __construct(&$db, $session_table, $session_data_table, $session_name = 'ECS_ID', $session_id = '') { 
        $this->cls_session($db, $session_table, $session_data_table, $session_name, $session_id);
    }

    function cls_session(&$db, $session_table, $session_data_table, $session_name = 'ECS_ID', $session_id = '') {
      // 将全局$_SESSION初始化为一个空数组并放进全局函数里
      $GLOBALS['_SESSION'] = array();
      //根据配置文件设置相关的类属性
      if (!empty($GLOBALS['cookie_path'])) {
        $this->session_cookie_path = $GLOBALS['cookie_path'];
      } else {
        $this->session_cookie_path = '/';
      }
      if (!empty($GLOBALS['cookie_domain'])) {
        $this->session_cookie_domain = $GLOBALS['cookie_domain'];
      } else {
        $this->session_cookie_domain = '';
      }
      # 这里稍微提一下,如果你使用的是HTTPS连接,那么这里需要设置为true
      if (!empty($GLOBALS['cookie_secure'])) {
        $this->session_cookie_secure = $GLOBALS['cookie_secure'];
      } else {
        $this->session_cookie_secure = false;
      }
      $this->session_name       = $session_name;
      $this->session_table      = $session_table;
      $this->session_data_table = $session_data_table;
      $this->db  = &$db;
      $this->_ip = real_ip();
      # 如果没有传递 Session ID ,就检查 cookie 中是否保存了
      if ($session_id == '' && !empty($_COOKIE[$this->session_name])) {
        $this->session_id = $_COOKIE[$this->session_name];
      } else {
        $this->session_id = $session_id;
      }
      # 如果存在 Session ID,则判断是否与加密的SessionID一样
      # 如果COOKIE中已经存在session_id,取他的前32位做CRC32位校检保证值的正确性
      if ($this->session_id) {
        $tmp_session_id = substr($this->session_id, 0, 32);
        if ($this->gen_session_key($tmp_session_id) == substr($this->session_id, 32)) {
          $this->session_id = $tmp_session_id;
        } else {
          $this->session_id = '';
        }
      }
      $this->_time = time();
      # 如果存在Session_id 就调用加载方法,否则就重新生成,并保存到 Cookie中
      if ($this->session_id) {
        # 从数据库中取对应session_id的记录保存到$_SESSION中
        $this->load_session();
      } else {
        # 如果COOKIE中无值或者没能通过校检则创建一个全新且唯一的session_id
        $this->gen_session_id();
        # 写COOKIE
        setcookie(
          $this->session_name,
          $this->session_id . $this->gen_session_key($this->session_id),
          time()+86400*7,
          $this->session_cookie_path,
          $this->session_cookie_domain,
          $this->session_cookie_secure
        );
      }
      register_shutdown_function(array(&$this, 'close_session'));
    }
    /** 生成一个唯一的session_id,并插入到数据库 */
    function gen_session_id() {
      $this->session_id = md5(uniqid(mt_rand(), true));
      return $this->insert_session();
    }
    /** 对COOKIE中的session_id做CRC32校检 */
    function gen_session_key($session_id) {
      static $ip = '';
      if ($ip == '') {
        $ip = substr($this->_ip, 0, strrpos($this->_ip, '.'));
      }
      return sprintf('%08x', crc32(ROOT_PATH . $ip . $session_id));
    }
    /** 如果数据库中对应COOKIE内session_id的记录已经不存在,则创建一条对应的空记录 */
    function insert_session() {
      $sql = 'INSERT INTO ' . $this->session_table . " (sesskey, expiry, ip, data) VALUES ('" . $this->session_id . "', '". $this->_time ."', '". $this->_ip ."', 'a:0:{}')";
      return $this->db->query($sql);
    }
    /** 检索对应session_id的记录,如果不存在则创建一条空记录 */
    function load_session() {
      $sSql = 'SELECT userid, adminid, user_name, user_rank, discount, email, data, expiry FROM ' . $this->session_table . " WHERE sesskey = '" . $this->session_id . "'";
      $session = $this->db->getRow($sSql);
      # 如果没有查询到相应的session,就重新初始化
      if (empty($session)) {
        $this->insert_session();
        $this->session_expiry = 0;
        $this->session_md5    = '40cd750bba9870f18aada2478b24840a';
        $GLOBALS['_SESSION']  = array();
      } else {
        // 如果Session中的data不是空的,且未过期
        if (!empty($session['data']) && $this->_time - $session['expiry'] <= $this->max_life_time) {
          $this->session_expiry = $session['expiry'];
          // 对记录的值做一个MD5校检,以检测后边SESSION值是否发生变化
          $this->session_md5    = md5($session['data']);
          // 反序列化$session['data']将值存到$_SESSION中
          $GLOBALS['_SESSION']  = unserialize($session['data']);
          $GLOBALS['_SESSION']['user_id'] = $session['userid'];
          $GLOBALS['_SESSION']['admin_id'] = $session['adminid'];
          $GLOBALS['_SESSION']['user_name'] = $session['user_name'];
          $GLOBALS['_SESSION']['user_rank'] = $session['user_rank'];
          $GLOBALS['_SESSION']['discount'] = $session['discount'];
          $GLOBALS['_SESSION']['email'] = $session['email'];
        } else {
          // 如果Session中的data是空的,则SESSION_DATA_TABLE表查询相应的Session记录
          $session_data = $this->db->getRow('SELECT data, expiry FROM ' . $this->session_data_table . " WHERE sesskey = '" . $this->session_id . "'");
          // 在SESSION_DATA_TABLE表中有数据且没有过期,则做相关赋值
          if (!empty($session_data['data']) && $this->_time - $session_data['expiry'] <= $this->max_life_time) {
            $this->session_expiry = $session_data['expiry'];
            // 对记录的值做一个MD5校检,以检测后边SESSION值是否发生变化
            $this->session_md5    = md5($session_data['data']);
            // 反序列化$session['data']将值存到$_SESSION中
            $GLOBALS['_SESSION']  = unserialize($session_data['data']);
            $GLOBALS['_SESSION']['user_id'] = $session['userid'];
            $GLOBALS['_SESSION']['admin_id'] = $session['adminid'];
            $GLOBALS['_SESSION']['user_name'] = $session['user_name'];
            $GLOBALS['_SESSION']['user_rank'] = $session['user_rank'];
            $GLOBALS['_SESSION']['discount'] = $session['discount'];
            $GLOBALS['_SESSION']['email'] = $session['email'];
          } else {
            $this->session_expiry = 0;
            $this->session_md5    = '40cd750bba9870f18aada2478b24840a';
            $GLOBALS['_SESSION']  = array();
          }
        }
      }
    }
    /** 更新Session 操作 */
    function update_session() {
      $adminid = !empty($GLOBALS['_SESSION']['admin_id']) ? intval($GLOBALS['_SESSION']['admin_id']) : 0;
      $userid  = !empty($GLOBALS['_SESSION']['user_id'])  ? intval($GLOBALS['_SESSION']['user_id'])  : 0;
      $user_name  = !empty($GLOBALS['_SESSION']['user_name'])  ? trim($GLOBALS['_SESSION']['user_name'])  : 0;
      $user_rank  = !empty($GLOBALS['_SESSION']['user_rank'])  ? intval($GLOBALS['_SESSION']['user_rank'])  : 0;
      $discount  = !empty($GLOBALS['_SESSION']['discount'])  ? round($GLOBALS['_SESSION']['discount'], 2)  : 0;
      $email  = !empty($GLOBALS['_SESSION']['email'])  ? trim($GLOBALS['_SESSION']['email'])  : 0;
      unset($GLOBALS['_SESSION']['admin_id']);
      unset($GLOBALS['_SESSION']['user_id']);
      unset($GLOBALS['_SESSION']['user_name']);
      unset($GLOBALS['_SESSION']['user_rank']);
      unset($GLOBALS['_SESSION']['discount']);
      unset($GLOBALS['_SESSION']['email']);
      $data        = serialize($GLOBALS['_SESSION']);
      $this->_time = time();
      // 如果页面上SESSION的值没有发生变化并且最后一次SESSION更新时间距离当前时间小于10秒则跳出函数
      if ($this->session_md5 == md5($data) && $this->_time < $this->session_expiry + 10) {
        return true;
      }
      // 转义SESSION的值用于安全入库
      $data = addslashes($data);
      # 如果data 超过255个字符就把数据移动到 session_data_table 表,并清空
      if (isset($data{255})) {
        $this->db->autoReplace($this->session_data_table, array('sesskey' => $this->session_id, 'expiry' => $this->_time, 'data' => $data), array('expiry' => $this->_time,'data' => $data));
        $data = '';
      }
      // 更新SESSION个字段的值,主要作用是更新expiry这个字段,以此来判断用户是否处于活动状态
      $uSql = 'UPDATE ' . $this->session_table . " SET expiry = '" . $this->_time . "', ip = '" . $this->_ip . "', userid = '" . $userid . "', adminid = '" . $adminid . "', user_name='" . $user_name . "', user_rank='" . $user_rank . "', discount='" . $discount . "', email='" . $email . "', data = '$data' WHERE sesskey = '" . $this->session_id . "' LIMIT 1";
      return $this->db->query($uSql);
    }
    /** register_shutdown_function将调用这个函数进行SESSION的更新和删除过期数据的操作 */
    function close_session() {
      # 更新 Session
      $this->update_session();
      # 清除过期的会话,并优化表
      if (mt_rand(0, 2) == 2) {
        $this->db->query('DELETE FROM ' . $this->session_data_table . ' WHERE expiry < ' . ($this->_time - $this->max_life_time));
        $this->db->query('OPTIMIZE TABLE ' . $this->session_table);
      }
      if ((time() % 2) == 0) {
        $this->db->query('DELETE FROM ' . $this->session_table . ' WHERE expiry < ' . ($this->_time - $this->max_life_time));
        return $this->db->query('OPTIMIZE TABLE ' . $this->session_table);
      }
      return true;
    }
    // 清除指定管事员的session会话
    function delete_spec_admin_session($adminid) {
      if (!empty($GLOBALS['_SESSION']['admin_id']) && $adminid) {
        return $this->db->query('DELETE FROM ' . $this->session_table . " WHERE adminid = '$adminid'");
      } else {
        return false;
      }
    }
    // 清空$_SESSION
    function destroy_session() {
      # 此处清除了所有的SESSION,如果在同一个浏览器中登陆了商家后台与总后台,一个退出就全部退出了
      $GLOBALS['_SESSION'] = array();
      $this->db->query('DELETE FROM ' . $this->session_data_table . " WHERE sesskey = '" . $this->session_id . "' LIMIT 1");
      $this->db->query('DELETE FROM ' . $this->session_table . " WHERE sesskey = '" . $this->session_id . "' LIMIT 1");
      return $this->db->query('OPTIMIZE TABLE ' . $this->session_table);
    }
    // 返回Session ID
    function get_session_id() {
      return $this->session_id;
    }
    // 统计在线活动用户
    function get_users_count() {
      return $this->db->getOne('SELECT count(*) FROM ' . $this->session_table);
    }
  }
  ?>