所以,我试图将会话存储在 mysql 数据库中。一切似乎都很顺利,因为它会将数据写入会话表等。但是,我只是注意到我可以写出会话数据,尽管我的读取方法是空的。因此,如果您查看代码,最终的 echo 语句将写入“值”——即使定义了零逻辑。有任何想法吗?谢谢!
class SessionManagement{
private $_hostname;
private $_username;
private $_password;
private $_database;
private $_timeout;
public function __construct() {
$CI =& get_instance();
$CI->load->database();
$this->_hostname = $CI->db->hostname;
$this->_username = $CI->db->username;
$this->_password = $CI->db->password;
$this->_database = $CI->db->database;
$this->_timeout = 60 * 60 * 10;
}
public function _open()
{
return TRUE;
}
public function _close()
{
return TRUE;
}
public function _read($id)
{
mysql_connect($this->_hostname, $this->_username, $this->_password);
mysql_select_db($this->_database);
$id = mysql_real_escape_string($id);
$sql = "SELECT session_data
FROM sessions
WHERE session_id = '$id'";
if ($result = mysql_query($sql)) {
if (mysql_num_rows($result)) {
$record = mysql_fetch_assoc($result);
return $record['session_data'];
}
}
return '';
}
public function _write($id, $data)
{
mysql_connect($this->_hostname, $this->_username, $this->_password);
mysql_select_db($this->_database);
$id = mysql_real_escape_string($id);
$data = mysql_real_escape_string(base64_encode(serialize(strip_tags($data))));
$access = time() + $this->_timeout;
$sql = "REPLACE INTO session (session_id, session_data, session_expires) VALUES('$id','$data', $access)";
return mysql_query($sql);
}
public function _gc($max)
{
return TRUE;
}
public function _destroy($id)
{
mysql_connect($this->_hostname, $this->_username, $this->_password);
mysql_select_db($this->_database);
$id = mysql_real_escape_string($id);
$sql = "DELETE
FROM session
WHERE session_id = '$id'";
return mysql_query($sql);
}
}
ini_set("session.save_handler", "user");
session_name("test");
session_set_cookie_params(0, '/', '.test.com');
$s = new SessionManagement();
session_set_save_handler(
array($s, '_open'),
array($s, '_close'),
array($s, '_read'),
array($s, '_write'),
array($s, '_destroy'),
array($s, '_gc')
);
session_start();
$_SESSION['test'] = "value";
ECHO $_SESSION['test'];