How to create user session manage system in Yii2 with DbSession [closed]

久未见 提交于 2019-12-05 12:42:45

I Find this solutions to save my users user_id into session table

Yii2 database session - store additional attributes and user information

Logging out specified user, listing who's online by using DB sessions

But there is another problem in implementing this issue: how to classify user sessions based on their browser and platform, and I found this solution.

I added another column to the session database, and inside it, using this class and the code below I saved the browser information and user platform information.

'components' => [
    //...
    'session' => [
                'class' => 'yii\web\DbSession',
                'writeCallback' => function ($session) {
                    $user_browser = null;
                    if (!Yii::$app->user->isGuest) {
                        $browser = new \BrowserDetection();
                        $user_browser = "{$browser->getName()}-{$browser->getPlatform()}" . ($browser->is64bitPlatform() ? "(x64)" : "(x86)") . ($browser->isMobile() ? "-Mobile" : "-Desktop");
                    }
                    return [
                        'user_id' => Yii::$app->user->id,
                        'last_write' => new \yii\db\Expression('NOW()'),
                        'browser_platform' => $user_browser
                    ];
                }
            ],
   // ...
]

note : you add other data to your session table

But to find the current session, I encountered a problem when I checked Yii::$app->session->id and returned the empty string value and I found the solution in the link below.

Blank Session ID in Module's BeforeAction

in Yii2-Advanced I create frontend\components\baseController and extend all controllers from it and create beforeAction() and open session in it something like this:

namespace frontend\components;
class BaseController extends \yii\web\Controller
{
    public function beforeAction($action)
        {
            if (parent::beforeAction($action)) 
            {
                Yii::$app->session->open();
                return true;
            }
              return false;
    }
}

At the end I create ActiveRecord model for session database and use it in profile page to show or remove user sessions

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!