Getting Logged User Location

Sometime we want to know logged user’s detail such as time, ip address, latitute/longitude, and other derivation of the ip address. Of course we hope in the long future we could draw historical view of any user.

To do it, I propose simple method of using geoplugin.net.

At least we need just 3 steps:

  1. Create tabel user_login_data
  2. Modify params.php
  3. Modify LoginForm.php

Lets jump to it.

  1. Create table to store the data
CREATE TABLE `smf_login_data` (
  `id` int(11) UNSIGNED NOT NULL,
  `user_id` int(6) NOT NULL,
  `ip_address` varchar(300) COLLATE utf8mb4_unicode_ci NOT NULL,
  `country` varchar(300) COLLATE utf8mb4_unicode_ci NOT NULL,
  `created_at` datetime DEFAULT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;
  1. Modify params.php
    Open your params.php in your config. If you use advanced template it is located in common/config.

put this below code on top of your params.php.

/* To get client IP Address */
if (!empty($_SERVER['HTTP_CLIENT_IP'])) {
    $ip = $_SERVER['HTTP_CLIENT_IP'];
} else if (!empty($_SERVER['HTTP_X_FORWARDED_FOR'])) {
    $ip = $_SERVER['HTTP_X_FORWARDED_FOR'];
} else if (!empty($_SERVER['REMOTE_ADDR'])) {
    $ip = $_SERVER['REMOTE_ADDR'];
} else {
    $ip = false;
}

/* to convert the ip address */
$ip_info = unserialize(file_get_contents('http://www.geoplugin.net/php.gp?ip='.$ip));

$country = $ip_info['geoplugin_countryName'];
$city = $ip_info['geoplugin_city'];
/*=====*/

And make little modification of the existing file like this:

return [
    'adminEmail' => 'admin@sample.com',
    'supportEmail' => 'support@sample.com',
    'senderEmail' => 'noreply@sample.com',
    'senderName' => 'SENDER_NAME',
    'user.passwordResetTokenExpire' => 3600,
    'user.passwordMinLength' => 8,
    'ip_access' => $ip,
    'city_access' => $city,
    'country_access' => $country,
];
  1. Modify LoginForm.php

Open your LoginForm.php, if we use advanced template it is located in common/models. Modify the login function as follow:

    public function login()
    {
        if ($this->validate()) {

            Yii::$app->db->createCommand()->insert('smf_login_data',[
                'ip_address'=> \Yii::$app->params['ip_access'],
                'country' => \Yii::$app->params['country_access'],
                'city'=> \Yii::$app->params['city_access'],
                'user_id' => $this->username,
                'created_at' => date('Y-m-d H:i:s'),
                ])->execute();

                return Yii::$app->user->login($this->getUser(), $this->rememberMe ? 3600 * 24 * 30 : 0);
        }
        
        return false;
    }

Form now on, when any user login our web the LoginForm will always insert the table. Of course you need to create MVC if want to view the table records (which I do not describe in this tutorial).

That’s it.

3 Likes