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

理想情况下,我会尝试编写一个 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?

推荐答案

您可以使用免费、简单的 API,例如:

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

  • http://ipinfodb.com/ip_location_api.php
  • http://www.ipgeo.com/api/
  • http://ip2.cc/
  • http://www.geobytes.com/IpLocator.htm
  • https://iplocate.io/
  • 还有很多其他的.

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

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:

  • http://phpweby.com/software/ip2country

HTH!

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

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!

获得坐标后,您可以将其反向地理编码为国家/地区代码.还有像这样的 API:

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

  • 示例:http://ws.geonames.org/countryCode?lat=47.03&lng=10.2
  • 更多 API:http://www.geonames.org/export/ws-概览.html

2013 年 4 月更新
今天我推荐使用 Geocoder,这是一个 PHP 库,它可以很容易地对 IP 地址进行地理编码以及邮政地址数据.

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.

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

***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.

相关文章