让游客在他们的IP*问国家

时间:2022-11-29 22:48:32

I want to get visitors country via their IP... Right now I'm using this (http://api.hostip.info/country.php?ip=...... )

我想通过他们的IP来吸引游客。现在我正在使用这个(http://api.hostip.info/country.php?

Here is my code:

这是我的代码:

<?php

if (isset($_SERVER['HTTP_CLIENT_IP']))
{
    $real_ip_adress = $_SERVER['HTTP_CLIENT_IP'];
}

if (isset($_SERVER['HTTP_X_FORWARDED_FOR']))
{
    $real_ip_adress = $_SERVER['HTTP_X_FORWARDED_FOR'];
}
else
{
    $real_ip_adress = $_SERVER['REMOTE_ADDR'];
}

$cip = $real_ip_adress;
$iptolocation = 'http://api.hostip.info/country.php?ip=' . $cip;
$creatorlocation = file_get_contents($iptolocation);

?>

Well, it's working properly, but the thing is, this returns the country code like US or CA., and not the whole country name like United States or Canada.

它运行得很好,但问题是,这返回的是像我们或CA这样的国家代码,而不是像美国或加拿大那样的整个国家名。

So, is there any good alternative to hostip.info offers this?

那么,有什么比hostip。info更好的替代方法吗?

I know that I can just write some code that will eventually turn this two letters to whole country name, but I'm just too lazy to write a code that contains all countries...

我知道我可以只写一些代码,最终把这两个字母变成整个国家的名字,但我懒得写包含所有国家的代码……

P.S: For some reason I don't want to use any ready made CSV file or any code that will grab this information for me, something like ip2country ready made code and CSV.

P。S:出于某种原因,我不想使用任何现成的CSV文件或任何可以为我获取这些信息的代码,比如ip2country准备好的代码和CSV。

20 个解决方案

#1


401  

Try this simple PHP function.

尝试这个简单的PHP函数。

<?php

function ip_info($ip = NULL, $purpose = "location", $deep_detect = TRUE) {
    $output = NULL;
    if (filter_var($ip, FILTER_VALIDATE_IP) === FALSE) {
        $ip = $_SERVER["REMOTE_ADDR"];
        if ($deep_detect) {
            if (filter_var(@$_SERVER['HTTP_X_FORWARDED_FOR'], FILTER_VALIDATE_IP))
                $ip = $_SERVER['HTTP_X_FORWARDED_FOR'];
            if (filter_var(@$_SERVER['HTTP_CLIENT_IP'], FILTER_VALIDATE_IP))
                $ip = $_SERVER['HTTP_CLIENT_IP'];
        }
    }
    $purpose    = str_replace(array("name", "\n", "\t", " ", "-", "_"), NULL, strtolower(trim($purpose)));
    $support    = array("country", "countrycode", "state", "region", "city", "location", "address");
    $continents = array(
        "AF" => "Africa",
        "AN" => "Antarctica",
        "AS" => "Asia",
        "EU" => "Europe",
        "OC" => "Australia (Oceania)",
        "NA" => "North America",
        "SA" => "South America"
    );
    if (filter_var($ip, FILTER_VALIDATE_IP) && in_array($purpose, $support)) {
        $ipdat = @json_decode(file_get_contents("http://www.geoplugin.net/json.gp?ip=" . $ip));
        if (@strlen(trim($ipdat->geoplugin_countryCode)) == 2) {
            switch ($purpose) {
                case "location":
                    $output = array(
                        "city"           => @$ipdat->geoplugin_city,
                        "state"          => @$ipdat->geoplugin_regionName,
                        "country"        => @$ipdat->geoplugin_countryName,
                        "country_code"   => @$ipdat->geoplugin_countryCode,
                        "continent"      => @$continents[strtoupper($ipdat->geoplugin_continentCode)],
                        "continent_code" => @$ipdat->geoplugin_continentCode
                    );
                    break;
                case "address":
                    $address = array($ipdat->geoplugin_countryName);
                    if (@strlen($ipdat->geoplugin_regionName) >= 1)
                        $address[] = $ipdat->geoplugin_regionName;
                    if (@strlen($ipdat->geoplugin_city) >= 1)
                        $address[] = $ipdat->geoplugin_city;
                    $output = implode(", ", array_reverse($address));
                    break;
                case "city":
                    $output = @$ipdat->geoplugin_city;
                    break;
                case "state":
                    $output = @$ipdat->geoplugin_regionName;
                    break;
                case "region":
                    $output = @$ipdat->geoplugin_regionName;
                    break;
                case "country":
                    $output = @$ipdat->geoplugin_countryName;
                    break;
                case "countrycode":
                    $output = @$ipdat->geoplugin_countryCode;
                    break;
            }
        }
    }
    return $output;
}

?>

How to use:

如何使用:

Example1: Get visitor IP address details

示例1:获取访问者的IP地址详细信息

<?php

echo ip_info("Visitor", "Country"); // India
echo ip_info("Visitor", "Country Code"); // IN
echo ip_info("Visitor", "State"); // Andhra Pradesh
echo ip_info("Visitor", "City"); // Proddatur
echo ip_info("Visitor", "Address"); // Proddatur, Andhra Pradesh, India

print_r(ip_info("Visitor", "Location")); // Array ( [city] => Proddatur [state] => Andhra Pradesh [country] => India [country_code] => IN [continent] => Asia [continent_code] => AS )

?>

Example 2: Get details of any IP address. [Support IPV4 & IPV6]

示例2:获取任何IP地址的详细信息。(支持IPV4和IPV6)

<?php

echo ip_info("173.252.110.27", "Country"); // United States
echo ip_info("173.252.110.27", "Country Code"); // US
echo ip_info("173.252.110.27", "State"); // California
echo ip_info("173.252.110.27", "City"); // Menlo Park
echo ip_info("173.252.110.27", "Address"); // Menlo Park, California, United States

print_r(ip_info("173.252.110.27", "Location")); // Array ( [city] => Menlo Park [state] => California [country] => United States [country_code] => US [continent] => North America [continent_code] => NA )

?>

#2


42  

You can use a simple API from http://www.geoplugin.net/

您可以使用http://www.geoplugin.net/中的简单API

$xml = simplexml_load_file("http://www.geoplugin.net/xml.gp?ip=".getRealIpAddr());
echo $xml->geoplugin_countryName ;


echo "<pre>";
foreach ($xml as $key => $value)
{
    echo $key , "= " , $value ,  " \n" ;
}
echo "</pre>";

Function Used

函数使用

function getRealIpAddr()
{
    if (!empty($_SERVER['HTTP_CLIENT_IP']))   //check ip from share internet
    {
      $ip=$_SERVER['HTTP_CLIENT_IP'];
    }
    elseif (!empty($_SERVER['HTTP_X_FORWARDED_FOR']))   //to check ip is pass from proxy
    {
      $ip=$_SERVER['HTTP_X_FORWARDED_FOR'];
    }
    else
    {
      $ip=$_SERVER['REMOTE_ADDR'];
    }
    return $ip;
}

Output

输出

United States
geoplugin_city= San Antonio
geoplugin_region= TX
geoplugin_areaCode= 210
geoplugin_dmaCode= 641
geoplugin_countryCode= US
geoplugin_countryName= United States
geoplugin_continentCode= NA
geoplugin_latitude= 29.488899230957
geoplugin_longitude= -98.398696899414
geoplugin_regionCode= TX
geoplugin_regionName= Texas
geoplugin_currencyCode= USD
geoplugin_currencySymbol= $
geoplugin_currencyConverter= 1

It makes you have so many options you can play around with

它让你有很多选择可以选择

Thanks

谢谢

:)

:)

#3


18  

I tried Chandra's answer but my server configuration does not allow file_get_contents()

我尝试了Chandra的答案,但是我的服务器配置不允许file_get_contents()

PHP Warning: file_get_contents() URL file-access is disabled in the server configuration

PHP警告:file_get_contents() URL文件访问在服务器配置中被禁用

I modified Chandra's code so that it also works for servers like that using cURL:

我修改了钱德拉的代码,使它也适用于像这样使用cURL的服务器:

function ip_visitor_country()
{

    $client  = @$_SERVER['HTTP_CLIENT_IP'];
    $forward = @$_SERVER['HTTP_X_FORWARDED_FOR'];
    $remote  = $_SERVER['REMOTE_ADDR'];
    $country  = "Unknown";

    if(filter_var($client, FILTER_VALIDATE_IP))
    {
        $ip = $client;
    }
    elseif(filter_var($forward, FILTER_VALIDATE_IP))
    {
        $ip = $forward;
    }
    else
    {
        $ip = $remote;
    }
    $ch = curl_init();
    curl_setopt($ch, CURLOPT_URL, "http://www.geoplugin.net/json.gp?ip=".$ip);
    curl_setopt($ch, CURLOPT_HEADER, 0);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE);
    $ip_data_in = curl_exec($ch); // string
    curl_close($ch);

    $ip_data = json_decode($ip_data_in,true);
    $ip_data = str_replace('&quot;', '"', $ip_data); // for PHP 5.2 see *.com/questions/3110487/

    if($ip_data && $ip_data['geoplugin_countryName'] != null) {
        $country = $ip_data['geoplugin_countryName'];
    }

    return 'IP: '.$ip.' # Country: '.$country;
}

echo ip_visitor_country(); // output Coutry name

?>

Hope that helps ;-)

希望帮助;-)

#4


12  

Actually, you can call http://api.hostip.info/?ip=123.125.114.144 to get the information, which is presented in XML.

实际上,您可以调用http://api.hostip.info/?ip=123.125.114.144来获取信息,该信息以XML格式呈现。

#5


10  

Use MaxMind GeoIP (or GeoIPLite if you are not ready to pay).

使用MaxMind GeoIP(或GeoIPLite,如果您不准备付费)。

$gi = geoip_open('GeoIP.dat', GEOIP_MEMORY_CACHE);
$country = geoip_country_code_by_addr($gi, $_SERVER['REMOTE_ADDR']);
geoip_close($gi);

#6


10  

Use following services

使用以下服务

1) http://api.hostip.info/get_html.php?ip=12.215.42.19

1)http://api.hostip.info/get_html.php?ip=12.215.42.19

2)

2)

$json = file_get_contents('http://freegeoip.appspot.com/json/66.102.13.106');
$expression = json_decode($json);
print_r($expression);

3) http://ipinfodb.com/ip_location_api.php

3)http://ipinfodb.com/ip_location_api.php

#7


10  

Check out php-ip-2-country from code.google. The database they provide is updated daily, so it is not necessary to connect to an outside server for the check if you host your own SQL server. So using the code you would only have to type:

从code.google上查看php-ip-2-country。它们提供的数据库每天都会更新,因此如果您托管自己的SQL服务器,则不需要连接外部服务器进行检查。所以使用代码你只需要输入:

<?php
$ip = $_SERVER['REMOTE_ADDR'];

if(!empty($ip)){
        require('./phpip2country.class.php');

        /**
         * Newest data (SQL) avaliable on project website
         * @link http://code.google.com/p/php-ip-2-country/
         */
        $dbConfigArray = array(
                'host' => 'localhost', //example host name
                'port' => 3306, //3306 -default mysql port number
                'dbName' => 'ip_to_country', //example db name
                'dbUserName' => 'ip_to_country', //example user name
                'dbUserPassword' => 'QrDB9Y8CKMdLDH8Q', //example user password
                'tableName' => 'ip_to_country', //example table name
        );

        $phpIp2Country = new phpIp2Country($ip,$dbConfigArray);
        $country = $phpIp2Country->getInfo(IP_COUNTRY_NAME);
        echo $country;
?>

Example Code (from the resource)

示例代码(来自资源)

<?
require('phpip2country.class.php');

$dbConfigArray = array(
        'host' => 'localhost', //example host name
        'port' => 3306, //3306 -default mysql port number
        'dbName' => 'ip_to_country', //example db name
        'dbUserName' => 'ip_to_country', //example user name
        'dbUserPassword' => 'QrDB9Y8CKMdLDH8Q', //example user password
        'tableName' => 'ip_to_country', //example table name
);

$phpIp2Country = new phpIp2Country('213.180.138.148',$dbConfigArray);

print_r($phpIp2Country->getInfo(IP_INFO));
?>

Output

输出

Array
(
    [IP_FROM] => 3585376256
    [IP_TO] => 3585384447
    [REGISTRY] => RIPE
    [ASSIGNED] => 948758400
    [CTRY] => PL
    [CNTRY] => POL
    [COUNTRY] => POLAND
    [IP_STR] => 213.180.138.148
    [IP_VALUE] => 3585378964
    [IP_FROM_STR] => 127.255.255.255
    [IP_TO_STR] => 127.255.255.255
)

#8


10  

We can use geobytes.com to get the location using user IP address

我们可以使用geobytes.com获取用户IP地址的位置。

$user_ip = getIP();
$meta_tags = get_meta_tags('http://www.geobytes.com/IPLocator.htm?GetLocation&template=php3.txt&IPAddress=' . $user_ip);
echo '<pre>';
print_r($meta_tags);

it will return data like this

它会像这样返回数据

Array(
    [known] => true
    [locationcode] => USCALANG
    [fips104] => US
    [iso2] => US
    [iso3] => USA
    [ison] => 840
    [internet] => US
    [countryid] => 254
    [country] => United States
    [regionid] => 126
    [region] => California
    [regioncode] => CA
    [adm1code] =>     
    [cityid] => 7275
    [city] => Los Angeles
    [latitude] => 34.0452
    [longitude] => -118.2840
    [timezone] => -08:00
    [certainty] => 53
    [mapbytesremaining] => Free
)

Function to get user IP

函数获取用户IP

function getIP(){
if (isset($_SERVER["HTTP_X_FORWARDED_FOR"])){
    $pattern = "/^(([1-9]?[0-9]|1[0-9]{2}|2[0-4][0-9]|25[0-5]).){3}([1-9]?[0-9]|1[0-9]{2}|2[0-4][0-9]|25[0-5])$/";
    if(preg_match($pattern, $_SERVER["HTTP_X_FORWARDED_FOR"])){
            $userIP = $_SERVER["HTTP_X_FORWARDED_FOR"];
    }else{
            $userIP = $_SERVER["REMOTE_ADDR"];
    }
}
else{
  $userIP = $_SERVER["REMOTE_ADDR"];
}
return $userIP;
}

#9


9  

Try this simple one line code, You will get country and city of visitors from their ip remote address.

尝试这个简单的一行代码,您将从他们的ip远程地址获得国家和城市的访问者。

$tags = get_meta_tags('http://www.geobytes.com/IpLocator.htm?GetLocation&template=php3.txt&IpAddress=' . $_SERVER['REMOTE_ADDR']);
echo $tags['country'];
echo $tags['city'];

#10


8  

There is a well-maintained flat-file version of the ip->country database maintained by the Perl community at CPAN

Perl社区在CPAN上维护的ip->国家数据库有一个维护良好的平面文件版本

Access to those files does not require a dataserver, and the data itself is roughly 515k

访问这些文件不需要数据服务器,数据本身大约是515k

Higemaru has written a PHP wrapper to talk to that data: php-ip-country-fast

Higemaru编写了一个PHP包装器来处理这些数据:PHP -ip-country-fast

#11


7  

You can use a web-service from http://ip-api.com
in your php code, do as follow :

您可以在php代码中使用http://ip-api.com的web服务,如下所示:

<?php
$ip = $_REQUEST['REMOTE_ADDR']; // the IP address to query
$query = @unserialize(file_get_contents('http://ip-api.com/php/'.$ip));
if($query && $query['status'] == 'success') {
  echo 'Hello visitor from '.$query['country'].', '.$query['city'].'!';
} else {
  echo 'Unable to get location';
}
?>

the query have many other informations:

该查询还有许多其他信息:

array (
  'status'      => 'success',
  'country'     => 'COUNTRY',
  'countryCode' => 'COUNTRY CODE',
  'region'      => 'REGION CODE',
  'regionName'  => 'REGION NAME',
  'city'        => 'CITY',
  'zip'         => ZIP CODE,
  'lat'         => LATITUDE,
  'lon'         => LONGITUDE,
  'timezone'    => 'TIME ZONE',
  'isp'         => 'ISP NAME',
  'org'         => 'ORGANIZATION NAME',
  'as'          => 'AS NUMBER / NAME',
  'query'       => 'IP ADDRESS USED FOR QUERY',
)

#12


6  

Many different ways to do it...

有很多不同的方法……

Solution #1:

One third party service you could use is http://ipinfodb.com. They provide hostname, geolocation and additional information.

您可以使用的第三方服务是http://ipinfodb.com。它们提供主机名、地理位置和其他信息。

Register for an API key here: http://ipinfodb.com/register.php. This will allow you to retrieve results from their server, without this it will not work.

在这里注册一个API键:http://ipinfodb.com/register.php。这将允许您从他们的服务器检索结果,否则它将无法工作。

Copy and past the following PHP code:

复制并通过以下PHP代码:

$ipaddress = $_SERVER['REMOTE_ADDR'];
$api_key = 'YOUR_API_KEY_HERE';

$data = file_get_contents("http://api.ipinfodb.com/v3/ip-city/?key=$api_key&ip=$ipaddress&format=json");
$data = json_decode($data);
$country = $data['Country'];

Downside:

缺点:

Quoting from their website:

引用他们的网站:

Our free API is using IP2Location Lite version which provides lower accuracy.

我们的免费API使用IP2Location Lite版本,提供更低的准确度。

Solution #2:

This function will return country name using the http://www.netip.de/ service.

这个函数将使用http://www.netip.de/ service返回国家名。

$ipaddress = $_SERVER['REMOTE_ADDR'];
function geoCheckIP($ip)
{
    $response=@file_get_contents('http://www.netip.de/search?query='.$ip);

    $patterns=array();
    $patterns["country"] = '#Country: (.*?)&nbsp;#i';

    $ipInfo=array();

    foreach ($patterns as $key => $pattern)
    {
        $ipInfo[$key] = preg_match($pattern,$response,$value) && !empty($value[1]) ? $value[1] : 'not found';
    }

        return $ipInfo;
}

print_r(geoCheckIP($ipaddress));

Output:

输出:

Array ( [country] => DE - Germany )  // Full Country Name

#13


4  

Not sure if this is a new service but now (2016) the easiest way in php is to use geoplugin's php web service: http://www.geoplugin.net/php.gp:

不确定这是否是一个新服务,但现在(2016)php最简单的方法是使用geoplugin的php web服务:http://www.geoplugin.net/phpgp:

Basic usage:

基本用法:

// GET 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;
}

// CALL THE WEBSERVICE
$ip_info = unserialize(file_get_contents('http://www.geoplugin.net/php.gp?ip='.$ip));

They also provide a ready built class: http://www.geoplugin.com/_media/webservices/geoplugin.class.php.tgz?id=webservices%3Aphp&cache=cache

它们还提供了一个现成的构建类:http://www.geoplugin.com/_media/webservices/geoplugin.class.php.tgz?id=webservices%3Aphp&cache=cache

#14


4  

My service https://ipdata.co provides the country name in 5 languages! As well as the organisation, currency, timezone, calling code, flag and Tor Exit Node status data from any IPv4 or IPv6 address.

我的服务https://ipdata。co提供了5种语言的国家名称!以及组织、货币、时区、调用代码、标记和Tor从任何IPv4或IPv6地址退出节点状态数据。

It's also extremely scalable with 10 regions around the world each able to handle >800M calls daily!

它还具有极强的可扩展性,世界上有10个地区每天都能处理>8亿的电话!

The options include; English (en), German (de), Japanese (ja), French (fr) and Simplified Chinese (za-CH)

选项包括;英文(en)、德文(de)、日文(ja)、法文(fr)及简体中文(za-CH)

$ip = '74.125.230.195';
$details = json_decode(file_get_contents("https://api.ipdata.co/{$ip}"));
echo $details->country_name;
//United States
echo $details->city;
//Mountain View
$details = json_decode(file_get_contents("https://api.ipdata.co/{$ip}/zh-CN"));
echo $details->country_name;
//美国

#15


3  

I have a short answer for this question which I have used in a project. In my answer I have consider that you have visitor IP address

我对这个问题有一个简短的回答,我在一个项目中使用过。在我的回答中,我认为您有访问IP地址

$ip = "202.142.178.220";
$ipdat = @json_decode(file_get_contents("http://www.geoplugin.net/json.gp?ip=" . $ip));
//get ISO2 country code
if(property_exists($ipdat, 'geoplugin_countryCode')) {
    echo $ipdat->geoplugin_countryCode;
}
//get country full name
if(property_exists($ipdat, 'geoplugin_countryName')) {
    echo $ipdat->geoplugin_countryName;
}

If it helps you vote up my answer.

如果它能帮你把我的答案投票。

#16


2  

I am using ipinfodb.com api and getting exactly what you are looking for.

我正在使用ipinfodb.com api并得到您想要的。

Its completely free, you just need to register with them to get your api key. You can include their php class by downloading from their website or you can use url format to retrieve information.

它是完全免费的,你只需要注册它们就可以获得你的api密钥。你可以从他们的网站下载他们的php类,或者你可以使用url格式来检索信息。

Here's what I am doing:

以下是我正在做的:

I included their php class in my script and using the below code:

我将他们的php类包含在我的脚本中,并使用以下代码:

$ipLite = new ip2location_lite;
$ipLite->setKey('your_api_key');
if(!$_COOKIE["visitorCity"]){ //I am using cookie to store information
  $visitorCity = $ipLite->getCity($_SERVER['REMOTE_ADDR']);
  if ($visitorCity['statusCode'] == 'OK') {
    $data = base64_encode(serialize($visitorCity));
    setcookie("visitorCity", $data, time()+3600*24*7); //set cookie for 1 week
  }
}
$visitorCity = unserialize(base64_decode($_COOKIE["visitorCity"]));
echo $visitorCity['countryName'].' Region'.$visitorCity['regionName'];

Thats it.

这是它。

#17


2  

you can use http://ipinfo.io/ to get details of ip address Its easy to use .

您可以使用http://ipinfo。io/获取ip地址的详细信息,使用方便。

<?php
    function ip_details($ip)
    {
    $json = file_get_contents("http://ipinfo.io/{$ip}");
    $details = json_decode($json);
    return $details;
    }

    $details = ip_details(YoUR IP ADDRESS); 

    echo $details->city;
    echo "<br>".$details->country; 
    echo "<br>".$details->org; 
    echo "<br>".$details->hostname; /

    ?>

#18


2  

Replace 127.0.0.1 with visitors IpAddress.

用访问者IpAddress替换127.0.0.1。

$country = geoip_country_name_by_name('127.0.0.1');

Installation instructions are here, and read this to know how to obtain City, State, Country, Longitude, Latitude, etc...

安装说明在这里,阅读本文了解如何获得城市、州、国家、经度、纬度等。

#19


0  

The User Country API has exactly what you need. Here is a sample code using file_get_contents() as you originally do:

用户国家API完全符合您的需要。下面是使用file_get_contents()的示例代码:

$result = json_decode(file_get_contents('http://usercountry.com/v1.0/json/'.$cip), true);
$result['country']['name']; // this contains what you need

#20


0  

A one liner with an IP address to country API

具有到国家API的IP地址的一行

echo file_get_contents('https://ipapi.co/8.8.8.8/country_name/');

> United States

Example :

例子:

https://ipapi.co/country_name/ - your country

https://ipapi。有限公司/ country_name——你的国家

https://ipapi.co/8.8.8.8/country_name/ - country for IP 8.8.8.8

https://ipapi.co/8.8.8 country_name/ - IP 8.8.8.8.8的国家

#1


401  

Try this simple PHP function.

尝试这个简单的PHP函数。

<?php

function ip_info($ip = NULL, $purpose = "location", $deep_detect = TRUE) {
    $output = NULL;
    if (filter_var($ip, FILTER_VALIDATE_IP) === FALSE) {
        $ip = $_SERVER["REMOTE_ADDR"];
        if ($deep_detect) {
            if (filter_var(@$_SERVER['HTTP_X_FORWARDED_FOR'], FILTER_VALIDATE_IP))
                $ip = $_SERVER['HTTP_X_FORWARDED_FOR'];
            if (filter_var(@$_SERVER['HTTP_CLIENT_IP'], FILTER_VALIDATE_IP))
                $ip = $_SERVER['HTTP_CLIENT_IP'];
        }
    }
    $purpose    = str_replace(array("name", "\n", "\t", " ", "-", "_"), NULL, strtolower(trim($purpose)));
    $support    = array("country", "countrycode", "state", "region", "city", "location", "address");
    $continents = array(
        "AF" => "Africa",
        "AN" => "Antarctica",
        "AS" => "Asia",
        "EU" => "Europe",
        "OC" => "Australia (Oceania)",
        "NA" => "North America",
        "SA" => "South America"
    );
    if (filter_var($ip, FILTER_VALIDATE_IP) && in_array($purpose, $support)) {
        $ipdat = @json_decode(file_get_contents("http://www.geoplugin.net/json.gp?ip=" . $ip));
        if (@strlen(trim($ipdat->geoplugin_countryCode)) == 2) {
            switch ($purpose) {
                case "location":
                    $output = array(
                        "city"           => @$ipdat->geoplugin_city,
                        "state"          => @$ipdat->geoplugin_regionName,
                        "country"        => @$ipdat->geoplugin_countryName,
                        "country_code"   => @$ipdat->geoplugin_countryCode,
                        "continent"      => @$continents[strtoupper($ipdat->geoplugin_continentCode)],
                        "continent_code" => @$ipdat->geoplugin_continentCode
                    );
                    break;
                case "address":
                    $address = array($ipdat->geoplugin_countryName);
                    if (@strlen($ipdat->geoplugin_regionName) >= 1)
                        $address[] = $ipdat->geoplugin_regionName;
                    if (@strlen($ipdat->geoplugin_city) >= 1)
                        $address[] = $ipdat->geoplugin_city;
                    $output = implode(", ", array_reverse($address));
                    break;
                case "city":
                    $output = @$ipdat->geoplugin_city;
                    break;
                case "state":
                    $output = @$ipdat->geoplugin_regionName;
                    break;
                case "region":
                    $output = @$ipdat->geoplugin_regionName;
                    break;
                case "country":
                    $output = @$ipdat->geoplugin_countryName;
                    break;
                case "countrycode":
                    $output = @$ipdat->geoplugin_countryCode;
                    break;
            }
        }
    }
    return $output;
}

?>

How to use:

如何使用:

Example1: Get visitor IP address details

示例1:获取访问者的IP地址详细信息

<?php

echo ip_info("Visitor", "Country"); // India
echo ip_info("Visitor", "Country Code"); // IN
echo ip_info("Visitor", "State"); // Andhra Pradesh
echo ip_info("Visitor", "City"); // Proddatur
echo ip_info("Visitor", "Address"); // Proddatur, Andhra Pradesh, India

print_r(ip_info("Visitor", "Location")); // Array ( [city] => Proddatur [state] => Andhra Pradesh [country] => India [country_code] => IN [continent] => Asia [continent_code] => AS )

?>

Example 2: Get details of any IP address. [Support IPV4 & IPV6]

示例2:获取任何IP地址的详细信息。(支持IPV4和IPV6)

<?php

echo ip_info("173.252.110.27", "Country"); // United States
echo ip_info("173.252.110.27", "Country Code"); // US
echo ip_info("173.252.110.27", "State"); // California
echo ip_info("173.252.110.27", "City"); // Menlo Park
echo ip_info("173.252.110.27", "Address"); // Menlo Park, California, United States

print_r(ip_info("173.252.110.27", "Location")); // Array ( [city] => Menlo Park [state] => California [country] => United States [country_code] => US [continent] => North America [continent_code] => NA )

?>

#2


42  

You can use a simple API from http://www.geoplugin.net/

您可以使用http://www.geoplugin.net/中的简单API

$xml = simplexml_load_file("http://www.geoplugin.net/xml.gp?ip=".getRealIpAddr());
echo $xml->geoplugin_countryName ;


echo "<pre>";
foreach ($xml as $key => $value)
{
    echo $key , "= " , $value ,  " \n" ;
}
echo "</pre>";

Function Used

函数使用

function getRealIpAddr()
{
    if (!empty($_SERVER['HTTP_CLIENT_IP']))   //check ip from share internet
    {
      $ip=$_SERVER['HTTP_CLIENT_IP'];
    }
    elseif (!empty($_SERVER['HTTP_X_FORWARDED_FOR']))   //to check ip is pass from proxy
    {
      $ip=$_SERVER['HTTP_X_FORWARDED_FOR'];
    }
    else
    {
      $ip=$_SERVER['REMOTE_ADDR'];
    }
    return $ip;
}

Output

输出

United States
geoplugin_city= San Antonio
geoplugin_region= TX
geoplugin_areaCode= 210
geoplugin_dmaCode= 641
geoplugin_countryCode= US
geoplugin_countryName= United States
geoplugin_continentCode= NA
geoplugin_latitude= 29.488899230957
geoplugin_longitude= -98.398696899414
geoplugin_regionCode= TX
geoplugin_regionName= Texas
geoplugin_currencyCode= USD
geoplugin_currencySymbol= $
geoplugin_currencyConverter= 1

It makes you have so many options you can play around with

它让你有很多选择可以选择

Thanks

谢谢

:)

:)

#3


18  

I tried Chandra's answer but my server configuration does not allow file_get_contents()

我尝试了Chandra的答案,但是我的服务器配置不允许file_get_contents()

PHP Warning: file_get_contents() URL file-access is disabled in the server configuration

PHP警告:file_get_contents() URL文件访问在服务器配置中被禁用

I modified Chandra's code so that it also works for servers like that using cURL:

我修改了钱德拉的代码,使它也适用于像这样使用cURL的服务器:

function ip_visitor_country()
{

    $client  = @$_SERVER['HTTP_CLIENT_IP'];
    $forward = @$_SERVER['HTTP_X_FORWARDED_FOR'];
    $remote  = $_SERVER['REMOTE_ADDR'];
    $country  = "Unknown";

    if(filter_var($client, FILTER_VALIDATE_IP))
    {
        $ip = $client;
    }
    elseif(filter_var($forward, FILTER_VALIDATE_IP))
    {
        $ip = $forward;
    }
    else
    {
        $ip = $remote;
    }
    $ch = curl_init();
    curl_setopt($ch, CURLOPT_URL, "http://www.geoplugin.net/json.gp?ip=".$ip);
    curl_setopt($ch, CURLOPT_HEADER, 0);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE);
    $ip_data_in = curl_exec($ch); // string
    curl_close($ch);

    $ip_data = json_decode($ip_data_in,true);
    $ip_data = str_replace('&quot;', '"', $ip_data); // for PHP 5.2 see *.com/questions/3110487/

    if($ip_data && $ip_data['geoplugin_countryName'] != null) {
        $country = $ip_data['geoplugin_countryName'];
    }

    return 'IP: '.$ip.' # Country: '.$country;
}

echo ip_visitor_country(); // output Coutry name

?>

Hope that helps ;-)

希望帮助;-)

#4


12  

Actually, you can call http://api.hostip.info/?ip=123.125.114.144 to get the information, which is presented in XML.

实际上,您可以调用http://api.hostip.info/?ip=123.125.114.144来获取信息,该信息以XML格式呈现。

#5


10  

Use MaxMind GeoIP (or GeoIPLite if you are not ready to pay).

使用MaxMind GeoIP(或GeoIPLite,如果您不准备付费)。

$gi = geoip_open('GeoIP.dat', GEOIP_MEMORY_CACHE);
$country = geoip_country_code_by_addr($gi, $_SERVER['REMOTE_ADDR']);
geoip_close($gi);

#6


10  

Use following services

使用以下服务

1) http://api.hostip.info/get_html.php?ip=12.215.42.19

1)http://api.hostip.info/get_html.php?ip=12.215.42.19

2)

2)

$json = file_get_contents('http://freegeoip.appspot.com/json/66.102.13.106');
$expression = json_decode($json);
print_r($expression);

3) http://ipinfodb.com/ip_location_api.php

3)http://ipinfodb.com/ip_location_api.php

#7


10  

Check out php-ip-2-country from code.google. The database they provide is updated daily, so it is not necessary to connect to an outside server for the check if you host your own SQL server. So using the code you would only have to type:

从code.google上查看php-ip-2-country。它们提供的数据库每天都会更新,因此如果您托管自己的SQL服务器,则不需要连接外部服务器进行检查。所以使用代码你只需要输入:

<?php
$ip = $_SERVER['REMOTE_ADDR'];

if(!empty($ip)){
        require('./phpip2country.class.php');

        /**
         * Newest data (SQL) avaliable on project website
         * @link http://code.google.com/p/php-ip-2-country/
         */
        $dbConfigArray = array(
                'host' => 'localhost', //example host name
                'port' => 3306, //3306 -default mysql port number
                'dbName' => 'ip_to_country', //example db name
                'dbUserName' => 'ip_to_country', //example user name
                'dbUserPassword' => 'QrDB9Y8CKMdLDH8Q', //example user password
                'tableName' => 'ip_to_country', //example table name
        );

        $phpIp2Country = new phpIp2Country($ip,$dbConfigArray);
        $country = $phpIp2Country->getInfo(IP_COUNTRY_NAME);
        echo $country;
?>

Example Code (from the resource)

示例代码(来自资源)

<?
require('phpip2country.class.php');

$dbConfigArray = array(
        'host' => 'localhost', //example host name
        'port' => 3306, //3306 -default mysql port number
        'dbName' => 'ip_to_country', //example db name
        'dbUserName' => 'ip_to_country', //example user name
        'dbUserPassword' => 'QrDB9Y8CKMdLDH8Q', //example user password
        'tableName' => 'ip_to_country', //example table name
);

$phpIp2Country = new phpIp2Country('213.180.138.148',$dbConfigArray);

print_r($phpIp2Country->getInfo(IP_INFO));
?>

Output

输出

Array
(
    [IP_FROM] => 3585376256
    [IP_TO] => 3585384447
    [REGISTRY] => RIPE
    [ASSIGNED] => 948758400
    [CTRY] => PL
    [CNTRY] => POL
    [COUNTRY] => POLAND
    [IP_STR] => 213.180.138.148
    [IP_VALUE] => 3585378964
    [IP_FROM_STR] => 127.255.255.255
    [IP_TO_STR] => 127.255.255.255
)

#8


10  

We can use geobytes.com to get the location using user IP address

我们可以使用geobytes.com获取用户IP地址的位置。

$user_ip = getIP();
$meta_tags = get_meta_tags('http://www.geobytes.com/IPLocator.htm?GetLocation&template=php3.txt&IPAddress=' . $user_ip);
echo '<pre>';
print_r($meta_tags);

it will return data like this

它会像这样返回数据

Array(
    [known] => true
    [locationcode] => USCALANG
    [fips104] => US
    [iso2] => US
    [iso3] => USA
    [ison] => 840
    [internet] => US
    [countryid] => 254
    [country] => United States
    [regionid] => 126
    [region] => California
    [regioncode] => CA
    [adm1code] =>     
    [cityid] => 7275
    [city] => Los Angeles
    [latitude] => 34.0452
    [longitude] => -118.2840
    [timezone] => -08:00
    [certainty] => 53
    [mapbytesremaining] => Free
)

Function to get user IP

函数获取用户IP

function getIP(){
if (isset($_SERVER["HTTP_X_FORWARDED_FOR"])){
    $pattern = "/^(([1-9]?[0-9]|1[0-9]{2}|2[0-4][0-9]|25[0-5]).){3}([1-9]?[0-9]|1[0-9]{2}|2[0-4][0-9]|25[0-5])$/";
    if(preg_match($pattern, $_SERVER["HTTP_X_FORWARDED_FOR"])){
            $userIP = $_SERVER["HTTP_X_FORWARDED_FOR"];
    }else{
            $userIP = $_SERVER["REMOTE_ADDR"];
    }
}
else{
  $userIP = $_SERVER["REMOTE_ADDR"];
}
return $userIP;
}

#9


9  

Try this simple one line code, You will get country and city of visitors from their ip remote address.

尝试这个简单的一行代码,您将从他们的ip远程地址获得国家和城市的访问者。

$tags = get_meta_tags('http://www.geobytes.com/IpLocator.htm?GetLocation&template=php3.txt&IpAddress=' . $_SERVER['REMOTE_ADDR']);
echo $tags['country'];
echo $tags['city'];

#10


8  

There is a well-maintained flat-file version of the ip->country database maintained by the Perl community at CPAN

Perl社区在CPAN上维护的ip->国家数据库有一个维护良好的平面文件版本

Access to those files does not require a dataserver, and the data itself is roughly 515k

访问这些文件不需要数据服务器,数据本身大约是515k

Higemaru has written a PHP wrapper to talk to that data: php-ip-country-fast

Higemaru编写了一个PHP包装器来处理这些数据:PHP -ip-country-fast

#11


7  

You can use a web-service from http://ip-api.com
in your php code, do as follow :

您可以在php代码中使用http://ip-api.com的web服务,如下所示:

<?php
$ip = $_REQUEST['REMOTE_ADDR']; // the IP address to query
$query = @unserialize(file_get_contents('http://ip-api.com/php/'.$ip));
if($query && $query['status'] == 'success') {
  echo 'Hello visitor from '.$query['country'].', '.$query['city'].'!';
} else {
  echo 'Unable to get location';
}
?>

the query have many other informations:

该查询还有许多其他信息:

array (
  'status'      => 'success',
  'country'     => 'COUNTRY',
  'countryCode' => 'COUNTRY CODE',
  'region'      => 'REGION CODE',
  'regionName'  => 'REGION NAME',
  'city'        => 'CITY',
  'zip'         => ZIP CODE,
  'lat'         => LATITUDE,
  'lon'         => LONGITUDE,
  'timezone'    => 'TIME ZONE',
  'isp'         => 'ISP NAME',
  'org'         => 'ORGANIZATION NAME',
  'as'          => 'AS NUMBER / NAME',
  'query'       => 'IP ADDRESS USED FOR QUERY',
)

#12


6  

Many different ways to do it...

有很多不同的方法……

Solution #1:

One third party service you could use is http://ipinfodb.com. They provide hostname, geolocation and additional information.

您可以使用的第三方服务是http://ipinfodb.com。它们提供主机名、地理位置和其他信息。

Register for an API key here: http://ipinfodb.com/register.php. This will allow you to retrieve results from their server, without this it will not work.

在这里注册一个API键:http://ipinfodb.com/register.php。这将允许您从他们的服务器检索结果,否则它将无法工作。

Copy and past the following PHP code:

复制并通过以下PHP代码:

$ipaddress = $_SERVER['REMOTE_ADDR'];
$api_key = 'YOUR_API_KEY_HERE';

$data = file_get_contents("http://api.ipinfodb.com/v3/ip-city/?key=$api_key&ip=$ipaddress&format=json");
$data = json_decode($data);
$country = $data['Country'];

Downside:

缺点:

Quoting from their website:

引用他们的网站:

Our free API is using IP2Location Lite version which provides lower accuracy.

我们的免费API使用IP2Location Lite版本,提供更低的准确度。

Solution #2:

This function will return country name using the http://www.netip.de/ service.

这个函数将使用http://www.netip.de/ service返回国家名。

$ipaddress = $_SERVER['REMOTE_ADDR'];
function geoCheckIP($ip)
{
    $response=@file_get_contents('http://www.netip.de/search?query='.$ip);

    $patterns=array();
    $patterns["country"] = '#Country: (.*?)&nbsp;#i';

    $ipInfo=array();

    foreach ($patterns as $key => $pattern)
    {
        $ipInfo[$key] = preg_match($pattern,$response,$value) && !empty($value[1]) ? $value[1] : 'not found';
    }

        return $ipInfo;
}

print_r(geoCheckIP($ipaddress));

Output:

输出:

Array ( [country] => DE - Germany )  // Full Country Name

#13


4  

Not sure if this is a new service but now (2016) the easiest way in php is to use geoplugin's php web service: http://www.geoplugin.net/php.gp:

不确定这是否是一个新服务,但现在(2016)php最简单的方法是使用geoplugin的php web服务:http://www.geoplugin.net/phpgp:

Basic usage:

基本用法:

// GET 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;
}

// CALL THE WEBSERVICE
$ip_info = unserialize(file_get_contents('http://www.geoplugin.net/php.gp?ip='.$ip));

They also provide a ready built class: http://www.geoplugin.com/_media/webservices/geoplugin.class.php.tgz?id=webservices%3Aphp&cache=cache

它们还提供了一个现成的构建类:http://www.geoplugin.com/_media/webservices/geoplugin.class.php.tgz?id=webservices%3Aphp&cache=cache

#14


4  

My service https://ipdata.co provides the country name in 5 languages! As well as the organisation, currency, timezone, calling code, flag and Tor Exit Node status data from any IPv4 or IPv6 address.

我的服务https://ipdata。co提供了5种语言的国家名称!以及组织、货币、时区、调用代码、标记和Tor从任何IPv4或IPv6地址退出节点状态数据。

It's also extremely scalable with 10 regions around the world each able to handle >800M calls daily!

它还具有极强的可扩展性,世界上有10个地区每天都能处理>8亿的电话!

The options include; English (en), German (de), Japanese (ja), French (fr) and Simplified Chinese (za-CH)

选项包括;英文(en)、德文(de)、日文(ja)、法文(fr)及简体中文(za-CH)

$ip = '74.125.230.195';
$details = json_decode(file_get_contents("https://api.ipdata.co/{$ip}"));
echo $details->country_name;
//United States
echo $details->city;
//Mountain View
$details = json_decode(file_get_contents("https://api.ipdata.co/{$ip}/zh-CN"));
echo $details->country_name;
//美国

#15


3  

I have a short answer for this question which I have used in a project. In my answer I have consider that you have visitor IP address

我对这个问题有一个简短的回答,我在一个项目中使用过。在我的回答中,我认为您有访问IP地址

$ip = "202.142.178.220";
$ipdat = @json_decode(file_get_contents("http://www.geoplugin.net/json.gp?ip=" . $ip));
//get ISO2 country code
if(property_exists($ipdat, 'geoplugin_countryCode')) {
    echo $ipdat->geoplugin_countryCode;
}
//get country full name
if(property_exists($ipdat, 'geoplugin_countryName')) {
    echo $ipdat->geoplugin_countryName;
}

If it helps you vote up my answer.

如果它能帮你把我的答案投票。

#16


2  

I am using ipinfodb.com api and getting exactly what you are looking for.

我正在使用ipinfodb.com api并得到您想要的。

Its completely free, you just need to register with them to get your api key. You can include their php class by downloading from their website or you can use url format to retrieve information.

它是完全免费的,你只需要注册它们就可以获得你的api密钥。你可以从他们的网站下载他们的php类,或者你可以使用url格式来检索信息。

Here's what I am doing:

以下是我正在做的:

I included their php class in my script and using the below code:

我将他们的php类包含在我的脚本中,并使用以下代码:

$ipLite = new ip2location_lite;
$ipLite->setKey('your_api_key');
if(!$_COOKIE["visitorCity"]){ //I am using cookie to store information
  $visitorCity = $ipLite->getCity($_SERVER['REMOTE_ADDR']);
  if ($visitorCity['statusCode'] == 'OK') {
    $data = base64_encode(serialize($visitorCity));
    setcookie("visitorCity", $data, time()+3600*24*7); //set cookie for 1 week
  }
}
$visitorCity = unserialize(base64_decode($_COOKIE["visitorCity"]));
echo $visitorCity['countryName'].' Region'.$visitorCity['regionName'];

Thats it.

这是它。

#17


2  

you can use http://ipinfo.io/ to get details of ip address Its easy to use .

您可以使用http://ipinfo。io/获取ip地址的详细信息,使用方便。

<?php
    function ip_details($ip)
    {
    $json = file_get_contents("http://ipinfo.io/{$ip}");
    $details = json_decode($json);
    return $details;
    }

    $details = ip_details(YoUR IP ADDRESS); 

    echo $details->city;
    echo "<br>".$details->country; 
    echo "<br>".$details->org; 
    echo "<br>".$details->hostname; /

    ?>

#18


2  

Replace 127.0.0.1 with visitors IpAddress.

用访问者IpAddress替换127.0.0.1。

$country = geoip_country_name_by_name('127.0.0.1');

Installation instructions are here, and read this to know how to obtain City, State, Country, Longitude, Latitude, etc...

安装说明在这里,阅读本文了解如何获得城市、州、国家、经度、纬度等。

#19


0  

The User Country API has exactly what you need. Here is a sample code using file_get_contents() as you originally do:

用户国家API完全符合您的需要。下面是使用file_get_contents()的示例代码:

$result = json_decode(file_get_contents('http://usercountry.com/v1.0/json/'.$cip), true);
$result['country']['name']; // this contains what you need

#20


0  

A one liner with an IP address to country API

具有到国家API的IP地址的一行

echo file_get_contents('https://ipapi.co/8.8.8.8/country_name/');

> United States

Example :

例子:

https://ipapi.co/country_name/ - your country

https://ipapi。有限公司/ country_name——你的国家

https://ipapi.co/8.8.8.8/country_name/ - country for IP 8.8.8.8

https://ipapi.co/8.8.8 country_name/ - IP 8.8.8.8.8的国家