Home >Backend Development >PHP Tutorial >How to Get City, State, and Country from an IP Address using PHP and Third-Party APIs?

How to Get City, State, and Country from an IP Address using PHP and Third-Party APIs?

Mary-Kate Olsen
Mary-Kate OlsenOriginal
2024-12-23 06:41:13436browse

How to Get City, State, and Country from an IP Address using PHP and Third-Party APIs?

How to Get Location Information from an IP Address in PHP

In order to tailor your web page to visitors' unique locations, you need a reliable way to retrieve information such as city, state, and country based on their IP addresses. There are a variety of options available for doing this.

One approach is to download a free GeoIP database and perform the lookup locally. Alternatively, you can use a third-party service for remote lookups, a convenient option that eliminates setup hassle but adds latency.

One such third-party service is ipinfo.io. It offers various information about an IP address, including hostname, geolocation, network owner, and more.

For example:

$ curl ipinfo.io/8.8.8.8
{
  "ip": "8.8.8.8",
  "hostname": "google-public-dns-a.google.com",
  "loc": "37.385999999999996,-122.0838",
  "org": "AS15169 Google Inc.",
  "city": "Mountain View",
  "region": "CA",
  "country": "US",
  "phone": 650
}

Here is an example of how to use ipinfo.io in PHP:

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

You can also integrate ipinfo.io on the client side. Here's a jQuery example:

$.get("https://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");

The above is the detailed content of How to Get City, State, and Country from an IP Address using PHP and Third-Party APIs?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn