IT박스

PHP로 IP 주소 국가 가져 오기

itboxs 2020. 9. 5. 09:29
반응형

PHP로 IP 주소 국가 가져 오기


이상적으로는 모든 웹 브라우저에서 쿼리 할 수있는 PHP 스크립트를 작성하고 PHP 스크립트에 액세스 한 IP 주소의 국가를 반환합니다.

이것이 가능합니까 아니면 더 나은 해결책이 있습니까?


다음과 같이 사용할 수있는 간편한 무료 API가 있습니다.

가장 신뢰할 수있는 것은 당신에게 달려 있습니다. :)

그렇지 않으면 서버의 로컬 데이터베이스를 기반으로하는 스크립트가 있습니다. 하지만 데이터베이스 데이터는 정기적으로 업데이트해야합니다. 다음을 확인하십시오.

HTH!

편집 : 물론 프로젝트에 따라 HTML5 위치 기능 을 살펴볼 수도 있습니다. 아직 Internet Explorer에서 사용할 수는 없지만 (IE9에서 지원할 예정이며 아직 멀었습니다), 청중이 주로 모바일 장치를 사용하거나 Safari / Firefox를 사용하는 경우에는 확실히 살펴볼 가치가 있습니다!

좌표가 있으면이를 국가 코드로 역 지오 코딩 할 수 있습니다. 다시 다음과 같은 API가 있습니다.

업데이트, 2013 년 4 월
오늘 저는 IP 주소와 우편 주소 데이터를 매우 쉽게 지오 코딩 할 수있는 PHP 라이브러리 인 Geocoder 를 사용하는 것이 좋습니다 .

*** 업데이트, 2016
9 월 Google의 개인 정보 보호 정책이 변경되었으므로 서버에 HTPPS 인증서가 없거나 사용자가 위치 확인을 허용하지 않는 경우 HTML5 Geolocation API를 사용할 수 없습니다. 이제 사용자의 IP를 사용하여 PHP에서 체크인하거나 HTTPS 인증서를받을 수 있습니다.


이를 수행하는 다양한 웹 API가 있습니다. 다음은 내 서비스 http://ipinfo.io 를 사용하는 예입니다 .

$ip = $_SERVER['REMOTE_ADDR'];
$details = json_decode(file_get_contents("http://ipinfo.io/{$ip}"));
echo $details->country; // -> "US"

웹 API는 빠르고 쉬운 솔루션이지만 많은 조회를 수행해야하는 경우 자신의 컴퓨터에 IP-> 국가 데이터베이스를 갖는 것이 더 나은 솔루션입니다. MaxMind는 GeoIP를 포함한 다양한 PHP 라이브러리와 함께 사용할 수 있는 무료 데이터베이스제공합니다 .


MaxMind에서 ip-tables를 다운로드 할 수 있습니다.

http://www.maxmind.com/app/geolite

CSV를 데이터베이스로 가져옵니다 (ip_long_from + ip_long_to에 대한 색인을 만들어야 함). 그런 다음 간단히 수행 할 수 있습니다.

$iplong = ip2long($_SERVER['REMOTE_ADDR']);

// should use mysqli with prepared statements etc, but just an example
mysql_query("
    SELECT country
    FROM ip_table
    WHERE $iplong BETWEEN ip_long_from AND ip_long_to
    LIMIT 1
");

다음은 http://www.geoplugin.net/json.gp 를 사용하는 예입니다 .

$ip = $_SERVER['REMOTE_ADDR'];
$details = json_decode(file_get_contents("http://www.geoplugin.net/json.gp?ip={$ip}"));
echo $details;

위치 API를 사용 하여 IP 주소에서 국가를 가져올 수 있습니다.

암호

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

응답

   US 

여기에 바이올린이 있습니다. 응답은 text특정 필드 (예 : country여기) 를 쿼리 할 때 입니다. 디코딩이 필요하지 않고 코드에 연결하기 만하면됩니다.

PS 예를 들어 모든 필드를 원하는 경우 https://ipapi.co/8.8.8.8/json/응답은 JSON입니다.


"기타 기본 확장"에서 GeoIP 기능을 살펴보십시오. http://php.net/manual/en/book.geoip.php


I see there are a lot of answers, but no one of them mentions https://freegeoip.net/

You're allowed up to 15,000 queries per hour. I think that's enough in most of the cases. Otherwise, you should think about using local databases from MaxMind GeoIP.

Freegeoip is open-source and you can find sources on github, deploy it locally and get rid of the query limits.

Also, service provides latitude/longitude/timezone and other useful stuff.


$country_code = trim(file_get_contents("http://ipinfo.io/{$ip_address}/country"))

will get you the country code.


Install and use PHP's GeoIP extension if you can. On debian lenny:

sudo wget http://geolite.maxmind.com/download/geoip/database/GeoLiteCity.dat.gz
sudo gunzip GeoLiteCity.dat.gz
sudo mkdir -v /usr/share/GeoIP
sudo mv -v GeoLiteCity.dat /usr/share/GeoIP/GeoIPCity.dat

sudo apt-get install php5-geoip
# or sudo apt-get install php-geoip for PHP7

and then try it in PHP:

$ip = $_SERVER['REMOTE_ADDR'];
$country = geoip_country_name_by_name($ip);
echo 'The current user is located in: ' . $country;

returns:

The current user is located in: Cameroon

I found this blog post very helpful. It saved my day. http://www.techsirius.com/2014/05/simple-geo-tracking-system.html

Basically you need to install the IP database table and then do mysql query for the IP for location.

<?php
include 'config.php';
mysql_connect(DB_HOST, DB_USER, DB_PASSWORD) OR die(mysql_error());
mysql_select_db(DB_NAME) OR die(mysql_error());
$ip =  $_SERVER['REMOTE_ADDR'];
$long = sprintf('%u', ip2long($ip));
$sql = "SELECT * FROM `geo_ips` WHERE '$long' BETWEEN `ip_start` AND `ip_end`";
$result = mysql_query($sql) OR die(mysql_error());
$ip_detail = mysql_fetch_assoc($result);
if($ip_detail){
    echo $ip_detail['country']."', '".$ip_detail['state']."', '".$ip_detail['city'];
}
else{
    //Something wrong with IP
}

Here is another free API for geolocation requests: http://geoip.nekudo.com

Responses are in JSON format. Additionally the API sourcecode is available on github in case you need to setup your own API.


If you need to have a good and updated database, for having more performance and not requesting external services from your website, here there is a good place to download updated and accurate databases.

I'm recommending this because in my experience it was working excellent even including city and country location for my IP which most of other databases/apis failed to include/report my location except this service which directed me to this database.
(My ip location was from "Rasht" City in "Iran" when I was testing and the ip was: 2.187.21.235 equal to 45815275)

Therefore I recommend to use these services if you're unsure about which service is more accurate:

Database: http://lite.ip2location.com/databases

API Service: http://ipinfodb.com/ip_location_api.php


You can use https://ip-api.io/ to get country name, city name, latitude and longitude. It supports IPv6.

As a bonus it will tell if ip address is a tor node, public proxy or spammer.

Php Code:

$result = json_decode(file_get_contents('http://ip-api.io/json/64.30.228.118'));
var_dump($result);

Output:

{
"ip": "64.30.228.118",
"country_code": "US",
"country_name": "United States",
"region_code": "FL",
"region_name": "Florida",
"city": "Fort Lauderdale",
"zip_code": "33309",
"time_zone": "America/New_York",
"latitude": 26.1882,
"longitude": -80.1711,
"metro_code": 528,
"suspicious_factors": {
"is_proxy": false,
"is_tor_node": false,
"is_spam": false,
"is_suspicious": false
}

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.


Ipdata.co provides a scalable API to do this. With 10 global endpoints each able to handle >800M requests daily!

It also gives you the organisation, currency, timezone, calling code, flag and Tor Exit Node status data from any IPv4 or IPv6 address.

In php

php > $ip = '8.8.8.8';
php > $details = json_decode(file_get_contents("https://api.ipdata.co/{$ip}"));
php > echo $details->region;
California
php > echo $details->city;
Mountain View
php > echo $details->country_name;
United States
php > echo $details->location;
37.405991,-122.078514

Disclaimer

I built this service.


Use the widget www.feedsalive.com, to get the country informations & last page information as well.


You can try the services of https://www.geoip-db.com They provide a JSON or JSONP-callback solution.

<?php

    $json = file_get_contents("https://www.geoip-db.com/json");
    $data = json_decode($json);

    print $data->country_code . "<br>";
    print $data->country_name . "<br>";
    print $data->state . "<br>";
    print $data->city . "<br>";
    print $data->postal . "<br>";
    print $data->latitude . "<br>";
    print $data->longitude . "<br>";
    print $data->IPv4 . "<br>";

?>

참고URL : https://stackoverflow.com/questions/3650006/get-country-of-ip-address-with-php

반응형