使用 PHP 获取 IP 地址的国家/地区

发布于 2024-09-18 13:32:21 字数 99 浏览 6 评论 0原文

理想情况下,我尝试编写一个 PHP 脚本,我可以从任何 Web 浏览器查询该脚本,并返回访问 PHP 脚本的 IP 地址的国家/地区。

这可能吗或者有更好的解决方案吗?

Ideally I'm trying to put together a PHP script that I can query from any web browser and it returns the country of the IP address that accessed the PHP script.

Is this possible or is there a better solution?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(16

古镇旧梦 2024-09-25 13:32:21

您可以使用一些免费且简单的 API,例如:

哪一个看起来最值得信赖取决于您:)

否则,有些脚本是基于您服务器上的本地数据库的。不过,数据库数据需要定期更新。看看这个:

HTH!

编辑:
当然,根据您的项目,您可能需要查看 HTML5 位置 功能。您还不能在 Internet Explorer 上使用它们(IE9 将支持它,还有很长的路要走),但如果您的受众主要使用移动设备或使用 Safari/Firefox,那么绝对值得一看!

获得坐标后,您可以将它们反向地理编码为国家/地区代码。同样有这样的 API:

更新,2013 年 4 月
今天我建议使用 Geocoder,这是一个 PHP 库,可以非常轻松地对 IP 地址进行地理编码以及邮政地址数据。

***更新,2016 年 9 月
由于 Google 的隐私政策已发生变化,如果您的服务器没有 HTTPPS 证书或用户不允许您检查其位置,则您无法使用 HTML5 Geolocation API。现在您可以使用用户的 IP 并在 PHP 中签入或获取 HTTPS 证书。

There are free, easy APIs you can use, like those:

Which one looks the most trustworthy is up to you :)

Otherwise, there are scripts which are based on local databases on your server. The database data needs to be updated regularly, though. Check out this one:

HTH!

Edit:
And of course, depending on your project you might want to look at HTML5 Location features. You can't use them yet on the Internet Explorer (IE9 will support it, long way to go yet), but in case your audience is mainly on mobile devices or using Safari/Firefox it's definitely worth to look at it!

Once you have the coordinates, you can reverse geocode them to a country code. Again there are APIs like this one:

Update, April 2013
Today I would recommend using Geocoder, a PHP library which makes it very easy to geocode ip addresses as well as postal address data.

***Update, September 2016
Since Google's privacy politics has changed, you can't use HTML5 Geolocation API if your server doesn't have HTPPS certificate or user doesn't allow you check his location. So now you can use user's IP and check in in PHP or get HTTPS certificate.

云裳 2024-09-25 13:32:21

有多种 Web API 可以为您执行此操作。这是使用我的服务 http://ipinfo.io 的示例:

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

Web API 是一个很好的快速且简单的解决方案,但是如果你需要进行大量的查找,然后才能获得 IP ->您自己的计算机上的国家数据库是更好的解决方案。 MaxMind 提供免费数据库,您可以将其与各种 PHP 库一起使用,包括GeoIP

There are various web APIs that will do this for you. Here's an example using my service, http://ipinfo.io:

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

Web APIs are a nice quick and easy solution, but if you need to do a lot of lookups then having an IP -> country database on your own machine is a better solution. MaxMind offer a free database that you can use with various PHP libraries, including GeoIP.

╄→承喏 2024-09-25 13:32:21

您可以从 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
");

You can download ip-tables from MaxMind:

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

Import the CSV to your database (make sure to create an index for ip_long_from + ip_long_to). Then you can simply do:

$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
");
┼── 2024-09-25 13:32:21

以下是使用 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;

Here's an example using 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;
烈酒灼喉 2024-09-25 13:32:21
$country_code = trim(file_get_contents("http://ipinfo.io/{$ip_address}/country"))

将为您提供国家/地区代码。

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

will get you the country code.

℉服软 2024-09-25 13:32:21

查看“其他基本扩展”下的 GeoIP 功能。 http://php.net/manual/en/book.geoip.php

Look at the GeoIP functions under "Other Basic Extensions." http://php.net/manual/en/book.geoip.php

椒妓 2024-09-25 13:32:21

我看到有很多答案,但没有一个提到 https://freegeoip.net/

你'每小时最多允许 15,000 次查询。我认为在大多数情况下这已经足够了。否则,您应该考虑使用 MaxMind GeoIP 的本地数据库。

Freegeoip 是开源的,您可以在 github 上找到源代码,并进行部署本地并摆脱查询限制。

此外,服务还提供纬度/经度/时区和其他有用的内容。

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.

绾颜 2024-09-25 13:32:21

这是另一个用于地理定位请求的免费 API:
http://geoip.nekudo.com

响应采用 JSON 格式。此外,如果您需要设置自己的 API,则可以在 github 上获取 API 源代码。

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.

眼角的笑意。 2024-09-25 13:32:21

如果可以的话,安装并使用 PHP 的 GeoIP 扩展。在 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

上,然后在 PHP 中尝试:

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

返回:

The current user is located in: Cameroon

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
早乙女 2024-09-25 13:32:21

我发现这篇博文非常有帮助。它拯救了我的一天。
http://www.techsirius.com/2014/05/simple -geo-tracking-system.html

基本上你需要安装IP数据库表,然后对IP进行mysql查询以获取位置。

<?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
}

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
}
无人接听 2024-09-25 13:32:21

如果您需要一个良好且更新的数据库,以获得更高的性能并且不从您的网站请求外部服务,此处 有一个下载更新且准确的数据库的好地方。

我推荐这个,因为根据我的经验,它工作得很好,甚至包括我的 IP 的城市和国家位置,大多数其他数据库/api 都无法包括/报告我的位置,除了 此服务将我定向到此数据库。
(当我测试时,我的 IP 位置来自“伊朗”的“Rasht”城市,IP 为:< code>2.187.21.235 等于 45815275

因此,如果您不确定哪种服务更准确,我建议使用这些服务:

数据库:
http://lite.ip2location.com/databases

API 服务:
http://ipinfodb.com/ip_location_api.php

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

可可 2024-09-25 13:32:21

您可以尝试 https://www.geoip-db.com 的服务 他们提供 JSON 或 JSONP -回调解决方案。

<?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>";

?>

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>";

?>
三五鸿雁 2024-09-25 13:32:21

您可以使用 https://ip-api.io/ 获取国家名称、城市名称、纬度和经度。它支持 IPv6。

作为奖励,它会判断 IP 地址是否为 Tor 节点、公共代理或垃圾邮件发送者。

PHP 代码:

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

输出:

{
"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
}

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
}
囍孤女 2024-09-25 13:32:21

我在 IPLocate.io 上运行该服务,您可以通过一个简单的调用免费连接到该服务:

<?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);

$res 对象将包含您的地理位置字段,例如 countrycity 等。

查看 文档 了解更多信息。

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.

戈亓 2024-09-25 13:32:21

Ipdata.co 提供了一个可扩展的 API 来执行此操作。拥有 10 个全球端点,每个端点每天能够处理超过 8 亿个请求!

它还为您提供来自任何 IPv4 或 IPv6 地址的组织、货币、时区、呼叫代码、标志和 Tor 退出节点状态数据。

在 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

免责声明

中,我构建了此服务。

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.

月朦胧 2024-09-25 13:32:21

使用小部件 www.feedsalive.com 获取国家/地区信息和信息最后一页信息也是如此。

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

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文