IP에서 방문자 국가를 가져 오기
방문자의 IP를 통해 방문자의 국가를 확보하고 싶습니다 ... 현재이 기능을 사용하고 있습니다 ( http://api.hostip.info/country.php?ip= ......
내 코드는 다음과 같습니다.
<?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);
?>
글쎄, 제대로 작동하지만 문제는 미국이나 캐나다와 같은 국가 코드를 반환하지만 미국이나 캐나다와 같은 국가 이름은 반환하지 않는다는 것입니다.
그래서 hostip.info가 이것을 제공하는 좋은 대안이 있습니까?
나는이 두 글자를 전체 국가 이름으로 바꾸는 코드를 작성할 수는 있지만 모든 국가를 포함하는 코드를 작성하기에는 너무 게으르다 ...
추신 : 어떤 이유로 든 기성품 CSV 파일 또는 ip2country 기성품 코드 및 CSV와 같은 나 에게이 정보를 가져 오는 코드를 사용하고 싶지 않습니다.
이 간단한 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;
}
?>
사용하는 방법:
예 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 )
?>
예 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 )
?>
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 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;
}
산출
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
그것은 당신이 놀 수있는 많은 옵션을 가지고 있습니다
감사
:)
Chandra의 답변을 시도했지만 서버 구성에서 file_get_contents ()를 허용하지 않습니다.
PHP Warning: file_get_contents() URL file-access is disabled in the server configuration
나는 cURL을 사용하는 것과 같은 서버에서도 작동하도록 Chandra의 코드를 수정했습니다.
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('"', '"', $ip_data); // for PHP 5.2 see stackoverflow.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
?>
희망이 도움이됩니다 ;-)
실제로 http://api.hostip.info/?ip=123.125.114.144 를 호출 하여 XML로 표시되는 정보를 얻을 수 있습니다 .
MaxMind GeoIP (또는 지불 할 준비가되지 않은 경우 GeoIPLite)를 사용하십시오.
$gi = geoip_open('GeoIP.dat', GEOIP_MEMORY_CACHE);
$country = geoip_country_code_by_addr($gi, $_SERVER['REMOTE_ADDR']);
geoip_close($gi);
다음 서비스 이용
1) http://api.hostip.info/get_html.php?ip=12.215.42.19
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
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;
?>
예제 코드 (자원에서)
<?
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));
?>
산출
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
)
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);
이 같은 데이터를 반환합니다
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
)
사용자 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;
}
이 간단한 한 줄 코드를 사용해보십시오. 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'];
PHP 코드 에서 http://ip-api.com 의 웹 서비스를 사용할 수 있습니다
.
<?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';
}
?>
쿼리에는 다른 많은 정보가 있습니다.
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',
)
CPAN 의 Perl 커뮤니티가 유지 보수하는 ip-> country 데이터베이스의 잘 관리 된 플랫 파일 버전이 있습니다.
해당 파일에 액세스하려면 데이터 서버가 필요하지 않으며 데이터 자체는 약 515k입니다
Higemaru는 그 데이터와 대화하기 위해 PHP 래퍼를 작성했습니다 : php-ip-country-fast
그것을하는 많은 다른 방법들 ...
해결책 # 1 :
사용할 수있는 타사 서비스 중 하나는 http://ipinfodb.com 입니다. 호스트 이름, 지리적 위치 및 추가 정보를 제공합니다.
: 여기에 API 키를 등록 http://ipinfodb.com/register.php . 이렇게하면 서버에서 결과를 검색 할 수 있습니다. 그렇지 않으면 작동하지 않습니다.
다음 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'];
단점 :
그들의 웹 사이트에서 인용 :
우리의 무료 API는 낮은 정확도를 제공하는 IP2Location Lite 버전을 사용하고 있습니다.
해결책 # 2 :
이 기능은 http://www.netip.de/ 서비스를 사용하여 국가 이름을 반환 합니다.
$ipaddress = $_SERVER['REMOTE_ADDR'];
function geoCheckIP($ip)
{
$response=@file_get_contents('http://www.netip.de/search?query='.$ip);
$patterns=array();
$patterns["country"] = '#Country: (.*?) #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));
산출:
Array ( [country] => DE - Germany ) // Full Country Name
내 서비스 ipdata.co 는 5 개 언어로 국가 이름을 제공합니다! IPv4 또는 IPv6 주소의 조직, 통화, 시간대, 통화 코드, 플래그, 이동 통신사 데이터, 프록시 데이터 및 Tor 종료 노드 상태 데이터는 물론입니다.
이 답변은 '제한된'API 키를 사용하며 매우 제한적이며 몇 번의 호출 테스트에만 사용됩니다. 자신의 무료 API 키에 가입 하고 개발을 위해 매일 최대 1500 개의 요청을받습니다.
또한 전 세계 10 개 지역에서 초당 10,000 개 이상의 요청을 처리 할 수있어 확장 성이 뛰어납니다!
옵션은 다음과 같습니다. 영어 (en), 독일어 (de), 일본어 (ja), 프랑스어 (fr) 및 중국어 간체 (za-CH)
$ip = '74.125.230.195';
$details = json_decode(file_get_contents("https://api.ipdata.co/{$ip}?api-key=test"));
echo $details->country_name;
//United States
echo $details->city;
//Mountain View
$details = json_decode(file_get_contents("https://api.ipdata.co/{$ip}?api-key=test/zh-CN"));
echo $details->country_name;
//美国
이것이 새로운 서비스인지 확실하지 않지만 현재 (2016) PHP에서 가장 쉬운 방법은 geoplugin의 PHP 웹 서비스를 사용하는 것입니다 : http://www.geoplugin.net/php.gp :
기본 사용법 :
// 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));
또한 준비된 클래스를 제공합니다. http://www.geoplugin.com/_media/webservices/geoplugin.class.php.tgz?id=webservices%3Aphp&cache=cache
나는 ipinfodb.com
API를 사용 하고 있으며 당신이 찾고있는 것을 정확하게 얻고 있습니다.
완전히 무료이므로 API 키를 얻으려면 등록해야합니다. 웹 사이트에서 다운로드하여 PHP 클래스를 포함 시키거나 URL 형식을 사용하여 정보를 검색 할 수 있습니다.
내가하고있는 일은 다음과 같습니다.
스크립트에 아래 코드를 사용하여 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'];
그게 다야.
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; /
?>
127.0.0.1
방문자 IpAddress로 교체하십시오 .
$country = geoip_country_name_by_name('127.0.0.1');
설치 지침은 여기 에 있으며 도시, 주, 국가, 경도, 위도 등을 얻는 방법을 알아 보려면이 지침을 읽으십시오.
echo file_get_contents('https://ipapi.co/8.8.8.8/country_name/');
> United States
예 :
https://ipapi.co/country_name/- 귀하의 국가
https://ipapi.co/8.8.8.8.country_name/-IP 8.8.8.8 국가
프로젝트에서 사용한 짧은 답변이 있습니다. 내 대답에는 방문자 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;
}
사용자 국가 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
ipstack geo API를 사용하여 국가 및 도시 방문자를 확보 할 수 있습니다. 자신의 ipstack API를 가져 와서 아래 코드를 사용해야합니다.
<?php
$ip = $_SERVER['REMOTE_ADDR'];
$api_key = "YOUR_API_KEY";
$freegeoipjson = file_get_contents("http://api.ipstack.com/".$ip."?access_key=".$api_key."");
$jsondata = json_decode($freegeoipjson);
$countryfromip = $jsondata->country_name;
echo "Country: ". $countryfromip ."";
?>
출처 : ipstack API를 사용하여 방문자에게 국가 및 도시를 PHP로 가져 오기
이것은get_client_ip()
대부분의 답변이의 주요 기능에 포함 된 기능에 대한 보안 정보 일뿐 입니다 get_geo_info_for_this_ip()
.
같은 요청 헤더의 IP 데이터에 너무 많이 의존하지 않는 Client-IP
또는 X-Forwarded-For
그러나 실제로 우리의 서버와 클라이언트 사이에 확립 된 TCP 연결의 소스 IP에 의존해야, 그들은 아주 쉽게 스푸핑 할 수 있기 때문 $_SERVER['REMOTE_ADDR']
으로 '그것을 할 수있는 속이지 않는다
$_SERVER['HTTP_CLIENT_IP'] // can be spoofed
$_SERVER['HTTP_X_FORWARDED_FOR'] // can be spoofed
$_SERVER['REMOTE_ADDR']// can't be spoofed
스푸핑 된 IP의 국가를 확보하는 것은 좋지만 모든 보안 모델에서이 IP를 사용하면 (예 : 빈번한 요청을 보내는 IP 금지) 전체 보안 모델이 손상된다는 점에 유의하십시오. IMHO 프록시 서버의 IP 인 경우에도 실제 클라이언트 IP를 사용하는 것이 좋습니다.
나는 이것이 오래되었다는 것을 알고 있지만 여기에 다른 몇 가지 해결책을 시도했지만 구식이거나 null을 반환하는 것 같습니다. 이것이 내가 한 방법입니다.
를 사용 http://www.geoplugin.net/json.gp?ip=
하면 서비스에 가입하거나 비용을 지불 할 필요가 없습니다.
function get_client_ip_server() {
$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';
return $ipaddress;
}
$ipaddress = get_client_ip_server();
function getCountry($ip){
$curlSession = curl_init();
curl_setopt($curlSession, CURLOPT_URL, 'http://www.geoplugin.net/json.gp?ip='.$ip);
curl_setopt($curlSession, CURLOPT_BINARYTRANSFER, true);
curl_setopt($curlSession, CURLOPT_RETURNTRANSFER, true);
$jsonData = json_decode(curl_exec($curlSession));
curl_close($curlSession);
return $jsonData->geoplugin_countryCode;
}
echo "County: " .getCountry($ipaddress);
그리고 추가 정보를 원한다면 Json이 완전히 돌아옵니다.
{
"geoplugin_request":"IP_ADDRESS",
"geoplugin_status":200,
"geoplugin_delay":"2ms",
"geoplugin_credit":"Some of the returned data includes GeoLite data created by MaxMind, available from <a href='http:\/\/www.maxmind.com'>http:\/\/www.maxmind.com<\/a>.",
"geoplugin_city":"Current City",
"geoplugin_region":"Region",
"geoplugin_regionCode":"Region Code",
"geoplugin_regionName":"Region Name",
"geoplugin_areaCode":"",
"geoplugin_dmaCode":"650",
"geoplugin_countryCode":"US",
"geoplugin_countryName":"United States",
"geoplugin_inEU":0,
"geoplugin_euVATrate":false,
"geoplugin_continentCode":"NA",
"geoplugin_continentName":"North America",
"geoplugin_latitude":"37.5563",
"geoplugin_longitude":"-99.9413",
"geoplugin_locationAccuracyRadius":"5",
"geoplugin_timezone":"America\/Chicago",
"geoplugin_currencyCode":"USD",
"geoplugin_currencySymbol":"$",
"geoplugin_currencySymbol_UTF8":"$",
"geoplugin_currencyConverter":1
}
시험
<?php
//gives you the IP address of the visitors
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 {
$ip = $_SERVER['REMOTE_ADDR'];
}
//return the country code
$url = "http://api.wipmania.com/$ip";
$country = file_get_contents($url);
echo $country;
?>
내 서비스를 사용할 수 있습니다 : https://SmartIP.io . IP 주소의 전체 국가 이름과 도시 이름을 제공합니다. 또한 시간대, 통화, 프록시 감지, TOR 노드 감지 및 암호화 감지를 노출합니다.
한 달에 250,000 건의 요청을 허용하는 무료 API 키를 등록하고 받으면됩니다.
공식 PHP 라이브러리를 사용하면 API 호출은 다음과 같습니다.
$apiKey = "your API key";
$smartIp = new SmartIP($apiKey);
$response = $smartIp->requestIPData("8.8.8.8");
echo "\nstatus code: " . $response->{"status-code"};
echo "\ncountry name: " . $response->country->{"country-name"};
자세한 내용은 API 설명서를 확인하십시오. https://smartip.io/docs
참고 URL : https://stackoverflow.com/questions/12553160/getting-visitors-country-from-their-ip
'Programing' 카테고리의 다른 글
Bash에서 두 변수 빼기 (0) | 2020.05.08 |
---|---|
비동기 기능의 조합 + 대기 + setTimeout (0) | 2020.05.08 |
UIImage와 Base64 문자열 간 변환 (0) | 2020.05.08 |
터미널을 통해 OS X에서 adb에 액세스 할 수 없습니다 (“명령을 찾을 수 없음”). (0) | 2020.05.08 |
앱이 설치되지 않은 것으로 보여도 [INSTALL_FAILED_UPDATE_INCOMPATIBLE] 실패 (0) | 2020.05.08 |