background image

PHP 中如何将 Session 保存到数据库

<?php 
class SessionToDB 

    private $_path         = null; 
    private $_name         = null; 
    private $_pdo          = null; 
    private $_ip           = null; 
    private $_maxLifeTime  = 0; 
     
    public function __construct(PDO $pdo) 
    { 
        session_set_save_handler( 
            array(&$this, 'open'), 
            array(&$this, 'close'), 
            array(&$this, 'read'), 
            array(&$this, 'write'), 
            array(&$this, 'destroy'), 
            array(&$this, 'gc')                                                             
        ); 
         
        $this->_pdo   = $pdo; 
 

           

 $this->_ip 

   

 =  !emptyempty($_SERVER['REMOTE_ADDR'])  ? 

$_SERVER['REMOTE_ADDR'] : null; 
        $this->_maxLifeTime = ini_get('session.gc_maxlifetime'); 
    } 
     
    public function open($path,$name) 
    { 
        return true;     
    } 
     
    public function close() 
    { 
        return true; 
    } 
     
    public function read($id) 
    { 
        $sql = 'SELECT * FROM session where PHPSESSID = ?'; 
        $stmt = $this->_pdo->prepare($sql); 
        $stmt->execute(array($id));