ecshop中的session机制不是PHP自带的,而是ecshop自定义的一套机制,这两天利用时间学习了一下,以下是学习笔记。
1.session的初始化是在 includes下的 init.php 文件中,具体代码如下:
1 if (!defined(‘INIT_NO_USERS‘)) 2 { 3 /* 初始化session */ 4 include(ROOT_PATH . ‘includes/cls_session.php‘); 5 6 $sess = new cls_session($db, $ecs->table(‘sessions‘), $ecs->table(‘sessions_data‘)); 7 8 define(‘SESS_ID‘, $sess->get_session_id()); 9 }
2.cls_session类的构造函数都做什么了?
(1)基础设置,清空session,为成员变量赋值,包括($this->session_cookie_path、$this->session_cookie_domain、$this->session_cookie_secure)
$GLOBALS[‘_SESSION‘] = array();//清空session 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 = ‘‘; } if (!empty($GLOBALS[‘cookie_secure‘])) { $this->session_cookie_secure = $GLOBALS[‘cookie_secure‘]; } else { $this->session_cookie_secure = false; } $this->session_name = $session_name; //session名称,默认 ‘ECS_ID‘ $this->session_table = $session_table; $this->session_data_table = $session_data_table; $this->db = &$db; $this->_ip = real_ip();//客户真实IP
(2)获取 session_id,如果cookie中存在就从cookie中获取,如果不存在就设置为空。
1 if ($session_id == ‘‘ && !empty($_COOKIE[$this->session_name])) 2 { 3 $this->session_id = $_COOKIE[$this->session_name]; 4 } 5 else 6 { 7 $this->session_id = $session_id; 8 }
(3)如果cookie中存在session_id,就效验此session_id的真实性
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 = ‘‘; } }
(4)如果session_id存在就加载该session_id下的session数据,如果不存在就生成一个session_id并插入到数据库
1 $this->_time = time(); 2 3 if ($this->session_id) 4 { 5 //如果存在session_id,加载该session_id 下的所有session 6 $this->load_session(); 7 } 8 else 9 { 10 $this->gen_session_id(); 11 12 setcookie($this->session_name, $this->session_id . $this->gen_session_key($this->session_id), 0, $this->session_cookie_path, $this->session_cookie_domain, $this->session_cookie_secure); 13 }
3.cls_session类其它重要方法
(1)gen_session_id() 生成一个session_id,并插入到数据库
function gen_session_id() { $this->session_id = md5(uniqid(mt_rand(), true)); return $this->insert_session(); }
(2)gen_session_key($session_id) 效验客户端session_id真实性
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)); }
(3)insert_session() 插入一条session
function insert_session() { return $this->db->query(‘INSERT INTO ‘ . $this->session_table . " (sesskey, expiry, ip, data) VALUES (‘" . $this->session_id . "‘, ‘". $this->_time ."‘, ‘". $this->_ip ."‘, ‘a:0:{}‘)"); }
(4)load_session() 通过session_id加载session
(5)update_session() 更新session
时间: 2024-10-08 00:57:27