Getting the location from an IP address

2019-06-14 13:43发布

I want to retrieve information like the city, state, and country of a visitor from their IP address, so that I can customize my web page according to their location. Is there a good and reliable way to do this in PHP? I am using JavaScript for client-side scripting, PHP for server-side scripting, and MySQL for the database.

24条回答
Root(大扎)
2楼-- · 2019-06-14 14:05

You need to use an external service... such as http://www.hostip.info/ if you google search for "geo-ip" you can get more results.

The Host-IP API is HTTP based so you can use it either in PHP or JavaScript depending on your needs.

查看更多
疯言疯语
3楼-- · 2019-06-14 14:05

Ok, guys, thanks for your suggestions; While i have 6k+ of IPs, some services will failed my requests due to some limitations; So, you could use them all in fallback mode;

If we have source file with following format:

user_id_1  ip_1
user_id_2  ip_2
user_id_3  ip_1

than you could use this simple expample command (PoC) for Yii:

class GeoIPCommand extends CConsoleCommand
{

public function actionIndex($filename = null)
{
    //http://freegeoip.net/json/{$ip} //10k requests per hour
    //http://ipinfo.io/{$ip}/json //1k per day
    //http://ip-api.com/json/{$ip}?fields=country,city,regionName,status //150 per minute

    echo "start".PHP_EOL;

    $handle      = fopen($filename, "r");
    $destination = './good_locations.txt';
    $bad         = './failed_locations.txt';
    $badIP       = [];
    $goodIP      = [];

    $destHandle = fopen($destination, 'a+');
    $badHandle  = fopen($bad, 'a+');

    if ($handle)
    {
        while (($line = fgets($handle)) !== false)
        {
            $result = preg_match('#(\d+)\s+(\d+\.\d+\.\d+\.\d+)#', $line, $id_ip);
            if(!$result) continue;

            $id = $id_ip[1];
            $ip = $id_ip[2];
            $ok = false;

            if(isset($badIP[$ip])) 
            {
                fputs($badHandle, sprintf('%u %s'. PHP_EOL, $id, $ip));
                continue;
            }

            if(isset($goodIP[$ip]))
            {
                fputs($destHandle, sprintf('"id":"%u","ip":"%s","from":"%s";'. PHP_EOL, $id, $ip, $goodIP[$ip]));
                echo sprintf('"id":"%s","ip":"%s","from":"%s";'. PHP_EOL, $id, $ip, $goodIP[$ip]);
                continue;
            }

            $query = @json_decode(file_get_contents('http://freegeoip.net/json/'.$ip));
            $city = property_exists($query, 'region_name')? $query->region_name : '';
            $city .= property_exists($query, 'city') && $query->city && ($query->city != $city) ? ', ' . $query->city : '';

            if($city)
            {
                fputs($destHandle, sprintf('"id":"%u","ip":"%s","from":"%s";'. PHP_EOL, $id, $ip, $city));
                echo sprintf('"id":"%s","ip":"%s","from":"%s";'. PHP_EOL, $id, $ip, $city);
                $ok = true;
            }

            if(!$ok)
            {
                $query = @json_decode(file_get_contents('http://ip-api.com/json/'. $ip.'?fields=country,city,regionName,status'));
                if($query && $query->status == 'success')
                {
                    $city = property_exists($query, 'regionName')? $query->regionName : '';
                    $city .= property_exists($query, 'city') && $query->city ? ',' . $query->city : '';

                    if($city)
                    {
                        fputs($destHandle, sprintf('"id":"%u","ip":"%s","from":"%s";'. PHP_EOL, $id, $ip, $city));
                        echo sprintf('"id":"%s","ip":"%s","from":"%s";'. PHP_EOL, $id, $ip, $city);
                        $ok = true;
                    }
                }
            }

            if(!$ok)
            {
                $badIP[$ip] = false;
                fputs($badHandle, sprintf('%u %s'. PHP_EOL, $id, $ip));
                echo sprintf('"id":"%s","ip":"%s","from":"%s";'. PHP_EOL, $id, $ip, 'Unknown');
            }

            if($ok)
            {
                $goodIP[$ip] = $city;
            }
        }

        fclose($handle);
        fclose($badHandle);
        fclose($destHandle);
    }else{
        echo 'Can\'t open file' . PHP_EOL; 
        return;
    }

    return;
}

}

This is some kind of shitty-code, but it works. usage:

./yiic geoip index --filename="./source_id_ip_list.txt"

Feel free to use, modify it, and do it better )

查看更多
我只想做你的唯一
4楼-- · 2019-06-14 14:08

Assuming you want to do it yourself and not rely upon other providers, IP2Nation provides a MySQL database of the mappings which are updated as the regional registries change things around.

查看更多
男人必须洒脱
5楼-- · 2019-06-14 14:09

This question is protected, which I understand. However, I do not see an answer here, what I see is a lot of people showing what they came up with from having the same question.

There are currently five Regional Internet Registries with varying degrees of functionality that serve as the first point of contact with regard to IP ownership. The process is in flux, which is why the various services here work sometimes and don't at other times.

Who Is is (obviously) an ancient TCP protocol, however -- the way it worked originally was by connection to port 43, which makes it problematic getting it routed through leased connections, through firewalls...etc.

At this moment -- most Who Is is done via RESTful HTTP and ARIN, RIPE and APNIC have RESTful services that work. LACNIC's returns a 503 and AfriNIC apparently has no such API. (All have online services, however.)

That will get you -- the address of the IP's registered owner, but -- not your client's location -- you must get that from them and also -- you have to ask for it. Also, proxies are the least of your worries when validating the IP that you think is the originator.

People do not appreciate the notion that they are being tracked, so -- my thoughts are -- get it from your client directly and with their permission and expect a lot to balk at the notion.

查看更多
太酷不给撩
6楼-- · 2019-06-14 14:09

I run the service at IPLocate.io, which you can hook into for free with one easy call:

<?php
$res = file_get_contents('https://www.iplocate.io/api/lookup/8.8.8.8');
$res = json_decode($res);

echo $res->country; // United States
echo $res->continent; // North America
echo $res->latitude; // 37.751
echo $res->longitude; // -97.822

var_dump($res);

The $res object will contain your geolocation fields like country, city, etc.

Check out the docs for more information.

查看更多
Bombasti
7楼-- · 2019-06-14 14:10

Using Google APIS:

<script type="text/javascript" src="http://www.google.com/jsapi"></script>
<script>
contry_code = google.loader.ClientLocation.address.country_code
city = google.loader.ClientLocation.address.city
region = google.loader.ClientLocation.address.region
</script>
查看更多
登录 后发表回答