gpt4 book ai didi

php - 在数据库中存储 session

转载 作者:行者123 更新时间:2023-11-30 23:13:15 25 4
gpt4 key购买 nike

我编写了这个帮助程序类来将 session 保存在数据库中,但它似乎根本不起作用。我检查了 session_set_save_handler 的返回值,它似乎总是返回一个 false 值,这意味着它无法首先设置处理程序函数。然后我尝试设置 session.auto_start = 0 和 session.save_handler = 'user' 但这似乎没有任何改变。我可以在 PHP.ini 中更改其他任何内容以使其正常工作,还是问题出在我的类(class)本身?

 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;
}
}

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

 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;

最佳答案

我通过查看此处的示例修复了它:

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

关于php - 在数据库中存储 session ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19013644/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com