D
D
djienbaev972020-02-15 11:27:17
Yii
djienbaev97, 2020-02-15 11:27:17

How to get the ip address of the user when entering the site?

I have a project in yii2 with online video tutorials, I need to do this, when a user enters the site from different devices (more than 3), he must be blocked so that he does not spread his account. Well, krch, he should only access the site from three devices. How to do this, who knows? How does it even work? Using ip addresses or using a token? If anyone has examples

Answer the question

In order to leave comments, you need to log in

1 answer(s)
V
Vlad Osadchyi, 2020-02-16
@VladOsadchyi

You can get the user's IP like this: Yii::$app->request->getUserIP();
IP checking can be done by adding the AccessManager filter to bootstrap
web.php:

$config = [
    ...
    'bootstrap' => [
        \app\components\user\AccessManager::class
    ],

access manager:
namespace app\components\user;

use yii\base\Component;
use Yii;

class AccessManager extends Component
{
    const ERROR_PAGE = 'site/error';

    public function init()
    {
        if (isset(Yii::$app->user) && !Yii::$app->user->isGuest) {
            $this->filtering();
        }
    }

    protected function filtering()
    {
        $user = Yii::$app->user->identity;
        $allowedIps = $user->getAllowedIps();
        if (!in_array(Yii::$app->request->getUserIP(), $allowedIps)) {
            Yii::$app->catchAll = [self::ERROR_PAGE];
        }
    }
}

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question