我编写了这个帮助类来将会话保存在数据库中,但它似乎根本不起作用。我检查了 session_set_save_handler 的返回值,它似乎总是返回一个 false 值,这意味着它首先无法设置处理程序函数。然后我尝试设置 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;