为什么要把session存入数据库?有什么用?
可以:统计在线人数,现实多站点session共享(通行证),控制同个账号登入人数等。
要实现session的入库,有关键的几个基本知识:
session.gc_divisor = 100 session.gc_probability = 1 。session.gc_probability 与 session.gc_divisor 合起来用来管理 gc(garbage collection 垃圾回收)进程启动的概率。( session.gc_probability/session.gc_divisor = 概率)
session.gc_maxlifetime = 1024 。session.gc_maxlifetime 指定过了多少秒之后数据就会被视为“垃圾”并被清除。
session.save_handler = files 。session.save_handler 定义了来存储和获取与会话关联的数据的处理器的名字。默认为 files。参见 session_set_save_handler()。
首先设计数据库表:
[sql]
CREATE TABLE IF NOT EXISTS `session` (
`phpsession` char(32) COLLATE utf8_bin NOT NULL,
`uptime` int(10) unsigned NOT NULL,
`data` text COLLATE utf8_bin NOT NULL, PRIMARY KEY (`phpsession`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_bin;
需要2个class, 一个是数据库的,一个是session的操作类
- <?php
- include 'DbSession.php';
- class MySession extends DbSession{
- private $dbc = null;
- private $lifetime = null;
- private $time = null;
-
- const uptime = 30;
-
- static $DEBUG = false;
-
- public function __construct( ){
- $this->init();
- $this->SessionSetSaveHandler();
- }
-
-
- private function init(){
- try{
-
- $db = DbSession::InitDbSession();
- if( !($db instanceof DbSession) ){
- throw new Exception('需要MySession类的对象');
- }else{
- $this->dbc = $db;
- }
-
- if( !$this->lifetime = ini_get('session.gc_maxlifetime') ){
- throw new Exception('session.gc_maxlifetime获取失败');
- }
- }catch (Exception $e){
- $this->ShowErrow( $e->getMessage() );
- }
- $this->time = time();
-
- }
-
-
- private function SessionSetSaveHandler(){
- session_set_save_handler(
- array($this, "open"),
- array($this, "close"),
- array($this, "read"),
- array($this, "write"),
- array($this, "destroy"),
- array($this, "gc")
- );
- session_start();
- }
-
-
- public function open($savePath, $sessName){
- if(is_null( $this->dbc )){
- return false;
- }else{
- return true;
- }
- }
-
-
- public function close(){
- $this->gc($this->lifetime);
- return $this->dbc->MysqlClose();
- }
-
-
- public function read( $sessionid ){
- $selectData = array(0=>$this->phpsession,1=>$this->uptime,2=>$this->data);
-
- $sessionData = $this->dbc->ReadSession($sessionid, $selectData);
-
- if( $sessionData == false){
- return false;
- }
-
-
- if( $sessionData[$this->uptime] + $this->lifetime < $this->time ){
- $this->destroy( $sessionData[$this->phpsession] );
- return false;
- }
-
- return $sessionData[$this->data];
- }
-
-
- public function write( $sessionid, $data ){
- $selectData = array(0=>$this->phpsession,1=>$this->uptime,2=>$this->data);
- $sessionData = $this->dbc->ReadSession($sessionid, $selectData);
- if( $sessionData == false){
- if( !empty( $data ) ){
-
- $insertData = array(
- $this->phpsession => $sessionid,
- $this->uptime => $this->time,
- $this->data => $data
- );
- $this->dbc->InsertSession( $insertData );
- }
- }else{
-
- if($sessionData[$this->data] != $data || $this->time > ($sessionData[$this->uptime]+self::uptime)){
-
- $updateData = array(
- $this->uptime => $this->time,
- $this->data => $data
- );
- $this->dbc->UpdateSession($sessionData[$this->phpsession], $updateData );
- }
- }
- return true;
- }
-
-
- public function destroy( $sessionid ){
-
- return $this->dbc->DeleteSession( $sessionid );
- }
-
-
- public function gc( $lifetime ){
- $this->dbc->GcSession( $lifetime );
- }
-
- }
-
- ?>
- <?php
-
- class DbSession{
- public static $db = null;
-
- private $con = null;
- private $HOSTNAME = 'localhost';
- private $DB = 'phptest';
- private $USER = 'root';
- private $PASSWORD = '';
- const CHARSET = 'UTF8';
-
- static $DEBUG = true;
-
-
- private $TableName = 'session';
- protected $phpsession = 'phpsession';
- protected $uptime = 'uptime';
- protected $data = 'data';
-
- private function __construct(){
- $this->contect();
- }
-
- private function __clone(){
-
- }
-
-
- public static function InitDbSession(){
- if( is_null(self::$db) || !(self::$db instanceof self) ){
- self::$db = new DbSession;
-
- }
- return self::$db;
- }
-
-
- private function contect(){
- $this->con = mysql_connect($this->HOSTNAME, $this->USER, $this->PASSWORD);
- try{
- if( is_null($this->con) ){
- throw new Exception('链接数据库失败');
- }
- if(!mysql_select_db($this->DB, $this->con)){
- throw new Exception('选择数据库失败');
- }
- mysql_query("SET NAMES self::CHARSET");
-
- }catch (Exception $e){
- $this->ShowErrow( $e->getMessage() );
- }
- }
-
- protected function ShowErrow( $msg ){
- if(static::$DEBUG){
- echo $msg;
- }
- }
-
-
- public function ReadSession( $sessionid, array $selectData ){
- $selectData = $this->doSelectData($selectData);
- if(!$selectData){
- return false;
- }
- if( $this->CheckSessionId($sessionid) ){
- $sql = 'SELECT '.$selectData.' FROM `'.$this->TableName.'` WHERE '.$this->phpsession.' = \''.$sessionid.'\' LIMIT 1';
- $result = mysql_query($sql, $this->con);
- return $this->fetch($result);
- }
- }
-
-
- public function InsertSession( array $insertData ){
- if( $insertData = $this->doInsertData($insertData) ){
- $sql = 'INSERT INTO '.$this->TableName.'('.$insertData[0].') VALUES('.$insertData[1].')';
- mysql_query($sql, $this->con);
- return true;
- }else{
- return false;
- }
- }
-
-
- public function UpdateSession( $sessionid, array $updateData){
- if( !$this->CheckSessionId($sessionid) ){
- return false;
- }
-
- if( $updateData = $this->doUpadateData($updateData) ){
- $sql = 'UPDATE '.$this->TableName.' SET '.$updateData.' WHERE '.$this->phpsession.' = \''.$sessionid.'\'';
- mysql_query($sql, $this->con);
- return true;
- }else{
- return false;
- }
- }
-
- public function DeleteSession( $sessionid ){
- if( !$this->CheckSessionId($sessionid) ){
- return false;
- }
- $sql = 'DELETE FROM '.$this->TableName.' WHERE \''.$sessionid.'\' = '.$this->phpsession;
- mysql_query($sql,$this->con);
- return true;
- }
-
-
- public function GcSession( $lifetime ){
- if( !ctype_digit($lifetime )){
- return false;
- }
- $checktime = time()-$lifetime;
- $sql = 'DELETE FROM '.$this->TableName.' WHERE '.$this->uptime.' < '.$checktime ;
- mysql_query($sql,$this->con);
- return true;
- }
-
-
- public function MysqlClose(){
- mysql_close( $this->con );
- }
-
- public function __destruct(){
- self::$db = null;
- if($this->con instanceof self){
- mysql_close( $this->con );
- }
- }
-
-
- private function CheckSessionId( $sessionid ){
- return ctype_alnum($sessionid);
- }
-
-
- private function fetch( $result ){
- if( $result && mysql_num_rows($result) == 1){
- $resultArray = array();
- $resultArray = mysql_fetch_array($result, MYSQL_ASSOC);
- if( !$resultArray || count($resultArray)== 0 ){
- return false;
- }else{
- return $resultArray;
- }
-
- }else{
- return false;
- }
- }
-
-
- private function doSelectData( array $data ){
- $keyString = '';
- foreach ($data as $value){
- $keyString .= '`'.$value.'`,';
- }
- $keyString = substr($keyString,0,-1);
- if($keyString == ''){
- return false;
- }
- return $keyString;
-
- }
-
-
- private function doInsertData( array $data ){
- $keyString = '';
- $valueString = '';
- if(array_key_exists($this->phpsession, $data)){
- if( !$this->CheckSessionId($data[$this->phpsession]) ){
- return false;
- }
- }
-
- foreach ($data as $key => $value){
- $keyString .= '`'.$key.'`,';
- if(ctype_digit($value)){
- $valueString .= ''.$value.',';
- }else{
- $valueString .= '\''.$value.'\',';
- }
-
- }
- if( $keyString != '' && $valueString != ''){
- $keyString = substr($keyString,0,-1);
- $valueString = substr($valueString,0,-1);
- $dataArray[0] = $keyString;
- $dataArray[1] = $valueString;
- return $dataArray;
- }else{
- return false;
- }
-
- }
-
-
- private function doUpadateData( array $data ){
- $upDataString = '';
-
- foreach($data as $key => $value){
- if(ctype_digit($value)){
- $value = ''.$value.'';
- }else{
- $value = '\''.$value.'\'';
- }
- $upDataString .= '`'.$key.'` = '.$value.',';
- }
- $upDataString = substr($upDataString,0,-1);
- if( $upDataString == ''){
- return false;
- }
- return $upDataString;
- }
-
- }
下面是使用方法:
- <?php
- include 'MySession.php';
-
- $session = new MySession( );
- $_SESSION['test1'] = 'test1';
- $_SESSION['test2'] = 2;
- $_SESSION['test3'] = array(1,2,3,4);
-
- ?>
|
请发表评论