在数据库中存储会话

时间:2013-09-25 19:33:04

标签: php mysql session

我编写了这个帮助程序类来保存数据库中的会话,但它似乎根本不起作用。我检查了session_set_save_handler的返回值,似乎它总是返回一个false值,这意味着它无法在第一时间设置handller函数。然后我尝试设置session.auto_start = 0和session.save_handler ='user',但这似乎没有改变任何东西。还有什么我可以在PHP.ini中更改以使其工作或问题出在我的班级本身?

 class Session 
 {
     private $db;

public function __construct ()
{
    //Instantiate new Database object
    $this->db = new Database ();

    // Set handler to overide SESSION
    $return = session_set_save_handler(
        array($this, "open"),
        array($this, "close"),
        array($this, "read"),
        array($this, "write"),
        array($this, "destroy"),
        array($this, "gc")
    );

            var_dump ($return);
    register_shutdown_function ('session_write_close') ;
    session_start ();  
}

/**
 * Open function
 * 
 * @param none
 * @return bool
 */
public function open ()
{
    if ($this->db) {
        return true;
    }
    return false;
}

    /**
 * Close function
 * 
 * @param none
 * @return bool
 */
public function close () 
{
    if($this->db->close ()) {
        return true;
    }

    return false;
}

/**
 * Read function
 * 
 * @param string $id
 * @return mixed
 */
public function read ($id)
{
    $this->db->query('SELECT data FROM sessions WHERE id = :id');
    $this->db->bind(':id', $id);

    if ($this->db->execute()) {
        $row = $this->db->single(); 
        return $row['data'];
    }

    return '';
}

/**
 * Write function
 * 
 * @param string $id
 * @param string $data
 * @return bool
 */
public function write ($id, $data)
{ 
    $access = time(); 
    $this->db->query('REPLACE INTO sessions VALUES (:id, :access, :data)');

    $this->db->bind(':id', $id);
    $this->db->bind(':access', $access);  
    $this->db->bind(':data', $data);

    if ($this->db->execute()){
        return true;
    }

    return false;
}

/**
 * Destroy function
 * 
 * @param string $id
 * @return bool
 */
public function destroy ($id)
{
  $this->db->query('DELETE FROM sessions WHERE id = :id');

  $this->db->bind(':id', $id);

  if ($this->db->execute ()) {
      return true;
  }

  return false;
} 

/**
 * Garbage collector function
 * 
 * @param int $maxLifeTime
 * @return bool
 */
public function gc ($maxLifeTime){
    $old = time() - $maxLifeTime;

    // Delete expired sessions from the database
    $this->db->query('DELETE * FROM sessions WHERE access < :old');     
    $this->db->bind(':old', $old);

    if($this->db->execute ()) {
        return true;
    }

    return false;
}
}

这是我用于存储会话的表的数据库结构:

 CREATE TABLE `sessions` (
  `id` char(32) NOT NULL,
  `data` text NOT NULL,
  `access` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
   PRIMARY KEY (`id`)
 ) ENGINE=InnoDB DEFAULT CHARSET=latin1;

1 个答案:

答案 0 :(得分:0)

我通过查看这里的示例修复了它:

http://phpsecurity.org/code/ch08-2