使用PHP获取IP地址的国家/地区 [英] Get Country of IP Address with PHP

查看:552
本文介绍了使用PHP获取IP地址的国家/地区的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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



这是可能的还是有更好的解决方案?

解决方案

您可以使用以下免费,简单的API:



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

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





HTH!



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



获得坐标后,您可以将其转换为国家/地区代码。再次有API像这样:





更新,2013年4月

今天, Geocoder ,这是一个PHP库,可以非常轻松地对IP地址和邮政地址数据进行地理编码。



*** 2016年9月更新 -
由于Google的隐私权政策已更改,因此如果您的服务器不具备HTML5地理定位API HTPPS证书或用户不允许您检查他的位置。因此,现在您可以使用用户的IP并使用PHP签入或获得HTTPS证书。


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?

解决方案

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.

这篇关于使用PHP获取IP地址的国家/地区的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆