Get Geolocation from IP Address with API in PHP

The Geolocation with IP address means identifying and retrieving the geographical location of a user from their IP address. Geolocation is mostly retrieved to get latitude/longitude of a user. Learn how to get geolocation from an IP address in PHP using an API service.

Get Geolocation from IP Address with API in PHP

Geolocation is mostly used by web applications that serve localized content to user based on user's IP address. In PHP user's IP address can be detected from global $_SERVER variable. From a user's IP Address we can then fetch the location data like latitude, longitude, street, city and country code. In this post we will learn how to get latitude, longitude, city, country and other data from user's IP address using a Geolocation API. Files we are going to create for this post:

  1. geolocation.php: Contains two function to get user IP address and fetch location data against that IP address.
  2. index.php: The HTML page containing the table with geolocation details.
  3. style.css: The CSS stylesheet for HTML and table.
 

What is a Geolocation API?

A geoloation API is an external service that provides API endpoints to fetch geolocation data from given IP address such as GeoJs and IPWHOIS.io API. We will use IPWHOIS API endpoint in this post to get country from IP address and other data in PHP as it provides detailed geographical data for given IP Address. IPWHOIS is free and very simple to use to get IP location data in PHP.

  • Tier: No registration required. unlimited usage except one request per second.
  • Provided Data: Latitude, Longitude, City, Country, Country Code and more.
  • API Endpointhttp://ipwhois.app/json/{ip}.

We are going to get user's geographical location data from their IP address using IPWHOIS API.

 

How to Get User Location Data From IP Address in PHP?

To retrieve geographical information from IP address we need two PHP functions. First we need a function to get user's IP address from $_SERVER variable. Second function to get geolocation data for retrieved IP address. We reate a file geolocation.php that will contain both functions to get current user's IP address and then fetch user's city and country and other data by IP.

  • Create a function get_client_ip_address() to fetch current user's IP address.
  • Create a function get_geolocation_from_ip_address() to fetch geolocation data from API for fetch IP address.

geolocation.php

<?php
/**
* @return string|null
*/
function get_client_ip_address(): ?string
{
$client_ip_address = null;

$ip_address = $_SERVER['HTTP_CLIENT_IP'] ??
$_SERVER['HTTP_X_FORWARDED_FOR'] ??
$_SERVER['HTTP_X_FORWARDED'] ??
$_SERVER['HTTP_FORWARDED_FOR'] ??
$_SERVER['HTTP_FORWARDED'] ??
$_SERVER['REMOTE_ADDR'];

foreach (explode(',', $ip_address) as $ip) {
if (filter_var($ip, FILTER_VALIDATE_IP, FILTER_FLAG_NO_RES_RANGE | FILTER_FLAG_NO_PRIV_RANGE)) {
$client_ip_address = $ip;
break;
}
}

return $client_ip_address;
}

/**
* @param string|null $ip_address
* @return string|null
*/
function get_geolocation_from_ip_address(?string $ip_address): ?string
{

$curl_handle = curl_init(sprintf('https://ipwhois.app/json/%s', $ip_address));

// Return response instead of outputting
curl_setopt($curl_handle, CURLOPT_RETURNTRANSFER, true);

// Execute API request
$curl_response = curl_exec($curl_handle);

// Close cURL resource
curl_close($curl_handle);

return $curl_response;
}

Display User Location Data From IP Address (PHP)

After declaring the two required functions that need to get user's geographical information, we can fetch and display country and other location data by user IP. Steps to get city and country from IP Address in PHP with API request:

  • Get user's IP Address and store it in a $client_ip_address variable.
  • Get geolocation data from API using $client_ip_address variable.
  • Decode the response from API using json_decode() function.
  • Display the geolocation data in an HTML table.

The API response has detailed data that can be used, but we are going to use following mostly used geolocation data:

  • IP Address: ip.
  • Latitude: latitude.
  • Longitude: longitude.
  • City: city.
  • Region: region.
  • Country: country.
  • Country Code: country_code.
  • Country Capital: country_capital.
  • Dialing Code: country_phone.
  • Timezone: timezone.

index.php

<?php
include_once 'functions.php';

$client_ip_address = get_client_ip_address();

$geolocation_data = json_decode(get_geolocation_from_ip_address($client_ip_address), true);
?>
<!DOCTYPE html>
<html>
<head>
<title>Get Geolocation from IP Address with API in PHP - Demo</title>
<meta content="text/html; charset=UTF-8" http-equiv="Content-Type"/>
<meta content="width=device-width, initial-scale=1, maximum-scale=1" name="viewport" />
<link rel="stylesheet" href="css/style.css" />
</head>
<body>
<section class="section py-4">
<div class="container">
<table class="table">
<thead>
<tr>
<th colspan="2">Geolocation Data</th>
</tr>
</thead>
<tbody>
<tr>
<th class="text-left" style="width: 200px;">IP Address</th>
<td><?= $geolocation_data['ip']; ?></td>
</tr>
<tr>
<th class="text-left">Latitude</th>
<td><?= $geolocation_data['latitude']; ?></td>
</tr>
<tr>
<th class="text-left">Longitude</th>
<td><?= $geolocation_data['longitude'] ;?></td>
</tr>
<tr>
<th class="text-left">City</th>
<td><?= $geolocation_data['city']; ?></td>
</tr>
<tr>
<th class="text-left">Region</th>
<td><?= $geolocation_data['region']; ?></td>
</tr>
<tr>
<th class="text-left">Country</th>
<td>
<img src="<?= $geolocation_data['country_flag']; ?>" width="15" height="15" />
<?= $geolocation_data['country']; ?>
</td>
</tr>
<tr>
<th class="text-left">Country Code</th>
<td><?= $geolocation_data['country_code']; ?></td>
</tr>
<tr>
<th class="text-left">Country Capital</th>
<td><?= $geolocation_data['country_capital']; ?></td>
</tr>
<tr>
<th class="text-left">Dialing Code</th>
<td><?= $geolocation_data['country_phone']; ?></td>
</tr>
<tr>
<th class="text-left">Timezone</th>
<td><?= $geolocation_data['timezone']; ?></td>
</tr>
</tbody>
</table>
</div>
</section>
</body>
</html>

Add CSS Styles for Geolocation Interface

Add CSS styles for entire HTML page and geolocation table.

style.css

* {
box-sizing: border-box;
}
html,body {
margin: 0;
padding: 0;
}
body {
background-color: #f6f6f6;
font-family: "Segoe UI", "Roboto", "Helvetica", sans-serif;
font-size: 15px;
font-weight: normal;
font-style: normal;
}
img {
max-width: 100%;
height: auto;
}
.container {
max-width: 1024px;
margin: 0 auto;
padding-left: 15px;
padding-right: 15px;
}
.py-4, .pt-4 {
padding-top: 1rem;
}
.py-4, .pb-4 {
padding-bottom: 1rem;
}
.text-left {
text-align: left;
}
.table {
display: table;
width: 100%;
border-collapse: collapse;
background-color: #ffffff;
}
.table th, .table td {
border-top: 1px solid #d1d5db;
}
.table th {
font-weight: 600;
padding: .75rem;
}
.table td {
padding: 0.345rem .75rem;
}
 

We now have a working script that we can use to get country from IP and other location from user's IP Address using an API. This is how the result will look like

Get Geolocation from IP Address in PHP using API - 01