Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

User IP address and location in Laravel 5.5

I am trying to get the ip address and location of user during registration...when user sign up for the first time I want to save the ip address and his location in the database in users table.

Please give me a solution to get the ip address and location of the new user...

Below is the line which i am using but this gives me wrong IP address of localhost...

127.0.0.1

$user = new User([
        'firstname' => $data['firstname'],
        'lastname' => $data['lastname'],
        'company' => $data['company'],
        'email' => $data['email'],
        'password' => bcrypt($data['password']),
        'phone' => $data['phone'],
        'country' => $data['country'],
        'zipcode' => $data['zipcode'],
        'city' => $data['city'],
        'state' => $data['state'] == "other" ? $data['custom_state'] : $data['state'],
        'ip_address' => request()->ip(),
    ]);
like image 641
MA-2016 Avatar asked Oct 02 '17 19:10

MA-2016


2 Answers

try this to get the ip address of user:

'ip_address' => \Request::ip();

and after getting an ip address you can get the location from that ip using below package.

https://github.com/stevebauman/location

'position' = Location::get(ip_address);

In the case of you get the localhost ip address then use this package to solve it: https://packagist.org/packages/fideloper/proxy

like image 82
RïshïKêsh Kümar Avatar answered Oct 25 '22 09:10

RïshïKêsh Kümar


    $ipaddress = '';
    if (isset($_SERVER['HTTP_CLIENT_IP'])) {
        $ipaddress = $_SERVER['HTTP_CLIENT_IP'];
    } else if (isset($_SERVER['HTTP_X_FORWARDED_FOR'])) {
        $ipaddress = $_SERVER['HTTP_X_FORWARDED_FOR'];
    } else if (isset($_SERVER['HTTP_X_FORWARDED'])) {
        $ipaddress = $_SERVER['HTTP_X_FORWARDED'];
    } else if (isset($_SERVER['HTTP_FORWARDED_FOR'])) {
        $ipaddress = $_SERVER['HTTP_FORWARDED_FOR'];
    } else if (isset($_SERVER['HTTP_FORWARDED'])) {
        $ipaddress = $_SERVER['HTTP_FORWARDED'];
    } else if (isset($_SERVER['REMOTE_ADDR'])) {
        $ipaddress = $_SERVER['REMOTE_ADDR'];
    } else {
        $ipaddress = 'UNKNOWN';
    }
    $json     = file_get_contents("http://ipinfo.io/$ipaddress/geo");
    $json     = json_decode($json, true);
    $country  = $json['country'];
    $region   = $json['region'];
    $city     = $json['city'];
like image 1
Adil Waheed Avatar answered Oct 25 '22 08:10

Adil Waheed