Check online users / set specific user offline

You are viewing revision #4 of this wiki article.
This is the latest version of this article.
You may want to see the changes made in this revision.

« previous (#3)

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