Answer the question
In order to leave comments, you need to log in
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
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
],
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 questionAsk a Question
731 491 924 answers to any question