简体   繁体   English

如何使用会话获取用户的在线时长?

[英]How to get online duration of a user by using session?

In yii I need to store the users _login time , logout time and total duration logged_ Using session. 在yii我需要存储用户_login timelogout time和记录的total duration logged_使用会话。

I am new to session concept. 我是会议概念的新手。 I don know how to retrieve the total logged time , login time , log out time . 我不知道如何检索total logged timelogin timelog out time In session table it stores only id--expire--data 在会话表中,它仅存储id--expire--data

My code for storing session is 我存储会话的代码是

protected/config/main.php

            'components'=>array(

    'session'=>array(
            'class' => 'CDbHttpSession',

            'connectionID' => 'db',
            'sessionTableName' => 'dbsession',
        ),
    ),

All working fine but data stored in db are encrypted. 一切正常,但存储在db中的数据是加密的。 So I am unable to retrieve the data I need. 所以我无法检索到我需要的数据。 One more thing what data is stored in session table. 还有一件事是什么数据存储在会话表中。

Alternative way I used without session but that also have problem. 替代方式我使用没有会话,但也有问题。 I used this for getting login time , logout time and total duration logged 我使用它来记录login timelogout timetotal duration logged

I used a table activity with fields 我在字段中使用了表活动

id,username,user_activity,url,ip,time 

Codes to fill datas in table when user login and logout is below 用户登录和注销时填写表中数据的代码如下

protected/controller/sitecontrollers.php

         public function actionLogin()
        {
                /* log in */

                $model=new LoginForm;

                // if it is ajax validation request
                if(isset($_POST['ajax']) && $_POST['ajax']==='login-form')
                {
                        echo CActiveForm::validate($model);
                        Yii::app()->end();
                }

                // collect user input data
                if(isset($_POST['LoginForm']))
                {
                        $model->attributes=$_POST['LoginForm'];
                        // validate user input and redirect to the previous page if valid
                        if($model->validate() && $model->login())                                                                               
                               {
                                $activity = new Activity;
                                $activity->username = Yii::app()->user->id;                          
                                //$activity->userId = Yii::app()->user->id;
                                $activity->user_activity = "1";
                $activity->url=$_SERVER['HTTP_REFERER'];
                $activity->ip=$_SERVER['REMOTE_ADDR'];
                                // This breaks the site when log in details are wrong
                                $activity->save();
                                if($activity->save())
                                $this->redirect(Yii::app()->homeUrl);
                    }                          


                }

                // display the login form
      if(Yii::app()->user->id==null)
      {
                  $this->render('login',array('model'=>$model));
      }
         else
           {
         throw new CHttpException(404,'User already logged in.');
             }
        }

        /**
         * Logs out the current user and redirect to homepage.
         */
       public function actionLogout()
        {


                // log
                $activity = new Activity;
                $activity->username = Yii::app()->user->id;
                $activity->user_activity = "0";
        $activity->url=$_SERVER['HTTP_REFERER'];
        $activity->ip=$_SERVER['REMOTE_ADDR'];
                $activity->save();      


                Yii::app()->user->logout();   
                                if($activity->save())                                  

                $this->redirect(Yii::app()->homeUrl);
        }

In this way all workin fine but when browser closed the application is logged out and a data not entering in to the database.then the calculation of duration is getting wrong. 通过这种方式所有工作都很好,但是当浏览器关闭时,应用程序将被注销,并且数据不会进入数据库。然后计算持续时间就会出错。 So only I took the method session but don't know how to use. 所以只有我参加了方法会议,但不知道如何使用。

i think you will never do such kind of thing corectly but with some mistake (more or less some minutes, depends on your needs). 我认为你永远不会做这样的事情,但有一些错误(或多或少几分钟,取决于你的需要)。

1. Keeping alive with page requests 1.通过页面请求保持活力

You could send alive status to your ajax page actionImAlive and more often you do that, more precisely you will tell how long user session was. 您可以发送活动状态,以你的Ajax网页actionImAlive多,往往你这样做,更准确地说 ,你会告诉用户会话多久。 If you do that alive thing 1 time in 5 minutes, you will have duration with ~5min mistake. 如果你在5分钟内做了1次活着 ,那么你将有5分钟的错误。

  1. Add columns t_login, t_last_activity 添加列t_login,t_last_activity
  2. on User login update t_login and t_last_activity with current timestamp 用户登录更新t_login和t_last_activity与当前时间戳
  3. On every user new page load check if need to update t_last_activity 在每个用户的新页面加载检查是否需要更新t_last_activity

    Main Controller *(components/Controller.php) 主控制器*(components / Controller.php)

     public function keepAlive( ) { User::model()->updateByPk( Yii::app()->user->id, // array('t_last_activity' => 'NOW()') //CURRENT_TIMESTAMP array('t_last_activity' => new CDbExpression('NOW()')) //CURRENT_TIMESTAMP..this working fine ); } // Runs after any action in controller public function afterAction($action) { self::keepAlive(); parent::afterAction($action); } // This action can be reached by ajax every 5min // if user stays in one page long enaugh // (write javascript..) public function actionImAlive() { self::keepAlive(); } 
  4. Above code updates t_last_activity every time user loads new page, but you could do it every 5min by saving last activity timestmap in user session and check it before executing keepAlive() function 上面的代码每次用户加载新页面时都会更新t_last_activity,但是你可以通过在用户会话中保存最后一个活动时间图并在执行keepAlive()函数之前检查它来每5分钟完成一次

    Other controllers 其他控制器

    All other controllers uses Controller class as parent 所有其他控制器使用Controller类作为父级

     SiteController extends Controller MyController extends Controller SomeController extends Controller 

2. For user display only (calculates duration from login time to now: now() - t_login ) 2.仅限用户显示(计算从登录时间到现在的持续时间: now() - t_login

If you want to display this session duration to user (why you should want to do this I don't know, but anyway..) you could just add t_login column to User table and calculate duration time on a fly. 如果你想向用户显示这个会话持续时间(为什么你应该这样做我不知道,但无论如何......)你可以将t_login列添加到User表并计算持续时间。

These was top of my head. 这些都是我的头脑。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM