需要关闭会话的数据库连接


Need to close database connection for session

我有以下代码,基本上是从http://www.spiration.co.uk/post/1333/PHP-5-sessions-in-mysql-database-with-PDO-db-objects

让我感到有点奇怪的是,那里没有任何东西可以关闭数据库连接(即设置$this->db = null)。我应该为此担心吗(或者这里的其他事情)?具体来说,我应该把$this->db = null在close()函数或close()这里意味着什么?:)

public $db;
public $maxlifetime = 1800; /* 30 mins */
public $expiry;
public function __destruct(){
session_write_close();
}
public function open( $path, $name ) {
$this->db = new PDO('mysql:host=' . MySQLConfigClass::MySql_SERVERNAME . ';dbname=' . MySQLConfigClass::MySql_DBNAME, MySQLConfigClass::MySql_LOGINNAME, MySQLConfigClass::MySql_PASS);
$this->db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
return true;
}
public function close() {
return true;
}
public function read($se_id){
$qry = "select se_value from sessions where se_id = '$se_id' and se_expires > " . time();
$sth = $this->db->prepare($qry);
$sth->execute();
$result = $sth->fetch(PDO::FETCH_ASSOC);
return $result['se_value'];
}
public function write($se_id, $se_val){
$this->expiry = time() + $this->maxlifetime;
try {
$qry= "insert into sessions (se_id, se_value, se_expires) values('$se_id', '$se_val', $this->expiry)";
$sth = $this->db->prepare($qry);
$sth->execute();
} catch (PDOException $e) {
$qry= "update sessions set se_value='$se_val', se_expires=$this->expiry where se_id='$se_id'";
$sth = $this->db->prepare($qry);
$sth->execute();
}
}
public function destroy($se_id){
$qry = "delete from sessions where se_id ='$se_id'";
$sth = $this->db->prepare($qry);
$tot= $sth->execute();
return ($tot);
}
public function gc($maxlifetime){
$qry = "delete from sessions where se_expires < ".time();
$sth = $this->db->prepare($qry);
$tot= $sth->execute();
return ($tot);
}
}
$session = new Session;
session_set_save_handler(
array(&$session, "open"),
array(&$session, "close"),
array(&$session, "read"),
array(&$session, "write"),
array(&$session, "destroy"),
array(&$session, "gc")
);
session_start();

在PDO中,一旦数据库对象(由new PDO()创建)被销毁,数据库连接将自动关闭。参见PHP PDO文档中的连接和连接管理。

如果您在创建PDO对象时设置了PDO::ATTR_PERSISTENT => true,那么该连接将被缓存并在后续页面加载时重用,前提是它们对数据库使用相同的凭据。

当您删除对PDO对象的所有引用时(例如通过将引用它的变量设置为null),连接将关闭。PHP退出时也会发生同样的事情。没有什么你必须做的。

另外,你可能有一些糟糕的SQL注入漏洞!您已经使用了准备好的查询…请确保对任何变量数据使用参数。