我想从其IP地址中检索访问者的城市,州和国家等信息,以便我可以根据其位置自定义我的网页。有没有一种好的可靠的方法来在PHP中做到这一点?我为客户端脚本使用JavaScript,服务器端脚本使用PHP,数据库使用MySQL。 您可以下载免费的GeoIP数据库并在本地查找IP地址,或者您可以使用第三方服务并执行远程查询。这是更简单的选项,因为它不需要设置,但确实会引入额外的延迟。
您可以使用的第三方服务是我的, http:// ipinfo。 IO 。他们提供主机名称,地理位置,网络所有者和其他信息,例如: $ $ $ $ curl ipinfo.io/8.8.8.8 {ip:8.8.8.8,主机名:google-public-dns-a.google,loc:37.385999999999996, - org:AS15169 Google Inc.,city:Mountain View,region:CA,country :美国,电话:650 }
PHP示例:
$ ip = $ _SERVER ['REMOTE_ADDR']; $ details = json_decode(file_get_contents(ipinfo.io/{$ip}/json)); echo $ details-> city; // - > Mountain View您也可以在客户端使用它。以下是一个简单的jQuery示例:
$。get(https:// ipinfo.io/json,函数(响应){$(#ip)。html(IP:+ response.ip); $(#address)。html(Location:+ response.city +,+ response.region); $(#details)。html(JSON.stringify(response,null,4));},jsonp);
< script src =ajax.googleapis/ajax/libs/jquery/1.11 .1 / jquery.min.js>< / script>< h3>客户端IP地理位置使用< a href =ipinfo.io> ipinfo.io< / a>< / h3>< hr />< div id =ip>< / div>< div id =address>< / div>< hr /> pre id =details>< / pre>
I want to retrieve information like the city, state, and country of a visitor from their IP address, so that I can customize my web page according to their location. Is there a good and reliable way to do this in PHP? I am using JavaScript for client-side scripting, PHP for server-side scripting, and MySQL for the database.
解决方案You could download a free GeoIP database and lookup the IP address locally, or you could use a third party service and perform a remote lookup. This is the simpler option, as it requires no setup, but it does introduce additional latency.
One third party service you could use is mine, ipinfo.io. They provide hostname, geolocation, network owner and additional information, eg:
$ curl ipinfo.io/8.8.8.8 { "ip": "8.8.8.8", "hostname": "google-public-dns-a.google", "loc": "37.385999999999996,-122.0838", "org": "AS15169 Google Inc.", "city": "Mountain View", "region": "CA", "country": "US", "phone": 650 }Here's a PHP example:
$ip = $_SERVER['REMOTE_ADDR']; $details = json_decode(file_get_contents("ipinfo.io/{$ip}/json")); echo $details->city; // -> "Mountain View"You can also use it client-side. Here's a simple jQuery example:
$.get("ipinfo.io/json", function (response) { $("#ip").html("IP: " + response.ip); $("#address").html("Location: " + response.city + ", " + response.region); $("#details").html(JSON.stringify(response, null, 4)); }, "jsonp");<script src="ajax.googleapis/ajax/libs/jquery/1.11.1/jquery.min.js"></script> <h3>Client side IP geolocation using <a href="ipinfo.io">ipinfo.io</a></h3> <hr/> <div id="ip"></div> <div id="address"></div> <hr/>Full response: <pre id="details"></pre>
更多推荐
从IP地址获取位置
发布评论