DEV Community

codedp
codedp

Posted on

Getting IP Geolocation Data in PHP

IP Geolocation is a technology that helps connect the online world with the real one. By linking IP addresses to geographical locations, it facilitates a variety of things such as customized user experiences, verification of identity, and adherence to local laws.

This guide is your manual for using the IpQuery.io API to fetch geolocation data in PHP. Along with our journey, we will also go through the wider concepts of geolocation, its accuracy, and its practical uses. We’ll get things rolling!

What Is IP Geolocation?
IP Geolocation is the process of assigning geographic locations to IP addresses. It achieves the same by referring to seemingly infinite databases maintained by entities such as regional Internet registries (e.g., ARIN, RIPE NCC) and ISPs. They are updated regularly to reflect changes in IP allocations.

IpQuery.io: A Simple Geolocation API for PHP
For those in need of a quick and straightforward way to get geolocation data for an IP address, IpQuery.io should be on their list. It does not require any API keys and the API calls return the required details via JSON response which can be parsed neatly.

Step 1: Making Your First API Call
Here is how it can be achieved by making the required API calls to IpQuery.io and getting the geolocation in PHP for a given IP address.

<?php
// The IP address you want to look up
$ipAddress = '8.8.8.8';

// Initialize a cURL session
$ch = curl_init();

// Set the API URL (no API key required!)
$url = "https://api.ipquery.io/?ip=$ipAddress&format=json";
curl_setopt($ch, CURLOPT_URL, $url);

// Set options to return the response as a string
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);

// Execute the request
$response = curl_exec($ch);

// Close the cURL session
curl_close($ch);

// Decode the JSON response
$data = json_decode($response, true);

// Check if the response contains valid data
if (isset($data['ip'])) {
    echo "IP Address: " . $data['ip'] . "
";
    echo "Country: " . $data['location']['country'] . "
";
    echo "City: " . $data['location']['city'] . "
";
    echo "ISP: " . $data['isp']['org'] . "
";
    echo "Is VPN: " . ($data['risk']['is_vpn'] ? 'Yes' : 'No') . "
";
} else {
    echo "Error: Unable to fetch geolocation data.
";
}
?>
Enter fullscreen mode Exit fullscreen mode

Step 2: Understanding the API Response
The API returns a JSON object that contains information on the queried IP address and such details as location and ISP from other queries.

IP Address: The number requested in the IP (For example 8.8.8.8).
Location: Nation, region, city, latitude, and longitude.
ISP: The Internet service provider's name and ASN.
Risk Indicators: A 'yes' or 'no' will be flagged for is_vpn, is_proxy, or is_tor.
Example Response:

{
  "ip": "8.8.8.8",
  "location": {
    "country": "United States",
    "region": "California",
    "city": "Mountain View"
  },
  "isp": {
    "asn": "15169",
    "org": "Google LLC"
  },
  "risk": {
    "is_vpn": false,
    "is_proxy": false,
    "is_tor": false
  }
}
Enter fullscreen mode Exit fullscreen mode

Step 3: Advanced Features
You are allowed to pare down your demands to fit the information that you specifically need. Let's say if you care only about the VPN condition and the country:

$url = "https://api.ipquery.io/?ip=$ipAddress&fields=location.country,risk.is_vpn&format=json";
This results in less data being returned which makes the requests become more efficient.

Applications of IP Geolocation

  1. Fraud Detection and Prevention
    Geolocation is used to identify possible fraudulent activities like logins coming from places miles away or areas which have high-risk VPNs.

  2. Personalized Content Delivery
    You can use geolocation to stream movies or videos from specific regions using Netflix or YouTube. Also, eCommerce shops can change units of price in local currency.

  3. Regulatory Compliance
    Services such as online gambling and streaming that come under the laws of specific regions can only be accessed depending on whether or not licensing agreements are in place.

  4. Targeted Advertising
    Advertisers have a chance to build hyper-local campaigns, thus they can promote a product in a specific city or country.

Challenges and Limitations
VPNs and Proxies In case users make their location disappear when using a VPN, the API will report the location that the VPN server is in rather than their real one.

Dynamic IPs A good number of residential IPs are changed in some given time intervals, hence the updating of the database is the basics for accuracy.

Mobile Networks Mobile users most times appear to be where their mobile operator's towers are despite the fact that they may be elsewhere.

Top comments (0)