李伟lwy

导航

mysql数据库保存sesison会话

<?php
header('Content-type:text/html;charset=gbk;');
date_default_timezone_set('PRC');
class db{
    private $conn=null;
    public function __construct($dsn,$user,$password){
        try{
            $this->conn = new PDO($dsn, $user, $password);
        }catch(PDOException $e){
            echo $e->getMessage();
            trigger_error('stopped',E_USER_ERROR);
        }
        
    }
    public function query($session_id){
        $sth=$this->conn->prepare('select session_id,session_data from session where session_id=? limit 1');
        $sth->execute(array($session_id));
        $result=$sth->fetch(PDO::FETCH_ASSOC);
        return $result['session_data'];
    }
    public function insert($session_id,$session_data){
        $sth=$this->conn->prepare('replace into session values(null,?,?,?)');
        $sth->execute(array($session_id,date('Y-m-d H:i:s'),$session_data));
        return true;
    }
    public function delete($where,$type=1){
        if($type==1){
            $sth=$this->conn->prepare('delete from session where session_id=?');
            $sth->execute(array($where));
        }elseif($type==2){
            $sth=$this->conn->prepare('delete from session where session_date<?');
            $sth->execute(array($where));
        }
        return true;
    }
}

class session_handler{
    private $db=null;
    public function __construct(db $obj){
        $this->db=$obj;
    }
    public function open($one,$two){
        return true;
    }
    public function close(){
        return true;
    }
    public function read($id){
        return (string)$this->db->query($id);
    }
    public function write($id,$data){
        $this->db->insert($id,$data);
        return true;
    }
    public function destroy($id){
        $this->db->delete($id);
        return true;
    }
    public function gc($maxlifetime){
        $this->db->delete(strtotime("Y-m-d H:i:s",time()-$maxlifetime),2);
        return true;
    }
}

$handler=new session_handler(new db('mysql:dbname=session;host=192.168.0.2','lwy','lwy'));
session_set_save_handler(
    array($handler, 'open'),
    array($handler, 'close'),
    array($handler, 'read'),
    array($handler, 'write'),
    array($handler, 'destroy'),
    array($handler, 'gc')
);
register_shutdown_function('session_write_close');
session_start();
$_SESSION['aa']='fffffffffeeeeeeeesssssssssssss';
$_SESSION['bb']='fefdsfgfsfsdfsd';
var_dump($_SESSION);

?>

php.ini session.save_handler=files 改为 session.save_handler=user
数据库session
表session
表创建sql:
CREATE TABLE `session` (
  `id` int(10) unsigned NOT NULL AUTO_INCREMENT,
  `session_id` varchar(100) DEFAULT NULL,
  `session_date` timestamp NULL DEFAULT NULL,
  `session_data` varchar(1024) DEFAULT NULL,
  PRIMARY KEY (`id`),
  UNIQUE KEY `session_id` (`session_id`)
)

 

 

posted on 2018-10-23 20:12  李伟lwy  阅读(260)  评论(0)    收藏  举报