0

我正在使用 Zend\Authentication 对用户进行身份验证,并在每次登录时都插入 session_id(),但它仍然允许使用相同的用户名进行多次登录。我已经尝试了一切,但完全不知道如何解决这个问题。这是我检查和插入会话的代码:

 public function indexAction()
 {

       $user = $this->identity();

       if ($this->getMembersTable()->checkSession($user->username) === false) {
           $_SESSION = array();
           session_destroy();
           setcookie(session_name(), '', time() - 300, '/', '', 0);

           return $this->redirect()->toUrl('/auth/login');
       }


    if (null === $user || empty($user)) {
        return $this->redirect()->toUrl('/auth/login');
    } 

    return array('user' => $user);
}


public function checkSession($username)<br>
{

    $sql = new Sql($this->table_gateway->getAdapter());<br>

    $adapter = $sql->getAdapter()->getDriver()->getConnection();

    $query = $adapter->execute("SELECT COUNT(*) FROM sessions WHERE username = 
         '$username' AND session_id = '" . md5(session_id()) . "'");

    if ($query->count() == 0) {
        return false;
    }
}

 public function insertSession($username, $password)
 {

    $sql = new Sql($this->table_gateway->getAdapter());


    $insert = new Insert('sessions');

    $adapter = $this->table_gateway->getAdapter();

    $insert->columns(array('username', 'password', 'active', 'session_id'))
      ->values(array('username' => $username, 'password' => $password, 'active' => 1, 'session_id' => md5(session_id())));

    $adapter->query(
        $sql->getSqlStringForSqlObject($insert),
        $adapter::QUERY_MODE_EXECUTE
    );


    return true;
}
4

1 回答 1

0

你的问题出在这里:

if ($query->count() == 0) {

count()返回找到的行数,但在COUNT(*)查询中,您始终只有一行。

试试这个:

$query = $adapter->execute("SELECT COUNT(*) as cnt FROM sessions WHERE username = '$username' AND session_id = '" . md5(session_id()) . "'");

if($query[0]['cnt'] == 0) { 
  // do your stuff here
}
于 2013-11-11T13:26:07.533 回答