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