1
我已經在數據庫中設置了會話存儲。當我撥打session_destroy
時,它會在數據庫中搜索特定session_id
以刪除它。爲什麼會話ID經常變化?
由於會話ID經常變化,新的session_id與之前存儲的db session_id不匹配,所以這些會話數據不會被刪除。即使gc也無法正常工作。所有會話數據都被保存到數據庫中,但不會被破壞。
DbSessionHandler.php
class DbSessionHandler implements SessionHandlerInterface{
public $dbconnect;
public function __construct($db){
$this->dbconnect=$db;
session_set_save_handler(
array($this, 'open'),
array($this, 'close'),
array($this, 'read'),
array($this, 'write'),
array($this, 'destroy'),
array($this, 'gc')
);
register_shutdown_function(session_write_close());
session_start();
}
//make sure whether db connection is successfull
public function open($savepath, $id)
{
return $this->dbconnect ? true : false;
}
public function close()
{
return true;
}
//read from database based on id, always return a string even if it is empty
public function read($id)
{
$data = ""; //declare empty string, if no data found, can return this empty string
$session_row = $this->dbconnect->prepare("select session_data from session_store where session_id=:id");
$session_row->execute(array(":id" => $id));
if ($session_row->rowCount() > 0) {
$datas = $session_row->fetch();
$data=$datas["session_data"];
}
return $data;
}
/**
* Write session_data using replace query (which does either insert or update)
*/
public function write($id, $data)
{
if(!(empty($data))) {
$time = time();
$session_write = $this->dbconnect->prepare("REPLACE INTO session_store VALUES(:id,:data,:expire)");
if ($session_write->execute(array(":id" => $id, ":data" => $data, ":expire" => $time))) {
return true;
}
}
return false;
}
/**
* Destroy
*/
public function destroy($id)
{
$destroy = $this->dbconnect->prepare("delete from session_store where session_id = :id");
if ($destroy->execute(array(":id" => $id))) {
return true;
}
return false;
}
/**
* Garbage Collection
*/
public function gc($max)
{
//Delete all records who have passed the expiration time
$time=time();
$delete = $this->dbconnect->prepare("delete from session_store where session_expire < :oldtime");
if ($delete->execute(array(":oldtime" => $time - $max))) {
return true;
}
return false;
}
}
其啓動會話php文件:
function initiate_session()
{
$session_hash = 'sha512';
$session_name = 'some_name';
$secure = false;
$httponly = true;
ini_set('session.use_only_cookies', 1);
ini_set('session.hash_function', $session_hash);
ini_set('session.hash_bits_per_character', 5);
$cookieParams = session_get_cookie_params();
session_set_cookie_params($cookieParams['lifetime'], $cookieParams['path'], $cookieParams['domain'], $secure, $httponly);
session_name($session_name);
new DbSessionHandler(db_connect());
}
在此圖片中,您可以看到,表中的session_id和腳本中的session_id不同,使得數據庫中的會話數據不會被刪除。
Session_id是否更改記錄的用戶或新用戶? –
登錄的用戶。有時會刪除一些會話記錄,因爲沒有會話ID更改。有時它不會因相同用戶的不同會話ID而被刪除。所以事情並不總是會話ID的變化。 – Learning