How to check the online users or how to logout a specific user from your admin panel? This wiki shows how to do that
1) In protected/config/main.php in components section add this
'session' => array(
//'class' => 'CDbHttpSession',
'class' => 'components.ExDbHttpSession',
'connectionID' => 'db',
'timeout' => 86400,
),
2) Extends the CDbHttpSession as components/ExDbHttpSession.php
class ExDbHttpSession extends CDbHttpSession {
public function setUserId($userId) {
$db = $this->getDbConnection();
$db->setActive(true);
$db->createCommand()->update(
$this->sessionTableName, array('id_user' => $userId),
'id=:id', array(':id' => session_id())
);
}
protected function createSessionTable($db, $tableName) {
parent::createSessionTable($db, $tableName);
$db->createCommand()->addColumn($tableName, 'id_user', 'integer');
}
public function getDbConnection() {
return parent::getDbConnection();
}
}
3) In the components/UserIdentity.php add the below code before the $this->errorCode = self::ERROR_NONE;
...
$this->id = $record->id;
Yii::app()->session->setUserId($this->id);
$this->errorCode = self::ERROR_NONE;
Also add this code
//override the getId method
public function getId() {
return $this->id;
}
In your User model add the below methods
//check whether the user is logged
public function isOnlineBySession() {
$table = Yii::app()->session->sessionTableName;
$db = Yii::app()->session->getDbConnection();
$row = $db->createCommand()->select()->from($table)->where('id_user=:id', array(':id' => $this->id))->queryRow();
if ($row) {
return true;
}
return false;
}
//force user to logout
public function logOutSession() {
$table = Yii::app()->session->sessionTableName;
$db = Yii::app()->session->getDbConnection();
$row = $db->createCommand()->delete($table, 'id_user=:id', array(':id' => $this->id));
if ($row)
return true;
return false;
}
Results:
- In your view/admin (CGridView) you can use the isOnlineBySession to display whether a user is online!
- In your controller you can use the logOutSession to logout any user
Works great !
Just for :
public function getId() { return $this->id; }
Replace to :
public function getId() { return $this->user->id; }
And you can forget this line :
$this->id = $this->id;
Really good, you can also get ALL users connected. It's exactly what I was looking for.
(Great tuto, for once...)
i got error like this
You are not authorized to perform this action.what it meant
If you have any questions, please ask in the forum instead.
Signup or Login in order to comment.