1
我編寫了這個幫助程序類來將會話保存在數據庫中,但它似乎根本無法工作。我檢查了session_set_save_handler的返回值,它似乎總是返回一個假值,這意味着它無法首先設置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;
你的類似乎缺少一個'close'方法 – rsanchez
我注意到,添加了一個close方法,但它仍然不起作用... – Ashesh