Guides
Last updated
August 7, 2023

How to geolocate an IP address in PHP

Shyam Purkayastha

Table of Contents:

Get your free
IP Geolocation
API key now
4.8 from 1,863 votes
See why the best developers build on Abstract
START FOR FREE
Thank you! Your submission has been received!
Oops! Something went wrong while submitting the form.
No credit card required

In a rush? Jump straight to the tutorial on how to geolocate an IP address with PHP.

The Internet is a vast swathe of the ever-growing data landscape, replete with web pages, social media posts, and various other sources. It helps propel a thriving virtual civilization by expediting the speed of information access and offers instant connectivity to information sources. At the same time, this virtual world relies on the physical world to bridge the gaps in information decimation. That's why, there is always a link between the virtual and physical worlds. The IP Geolocation is a vital element of this linkage.   

In this post, we explore the concept of IP Geolocation in detail, covering the basics to the advanced. We will address the importance of IP Geolocation in web development through code examples in PHP, and also explore some of the use case examples of IP geolocation in the real world.

What is IP Geolocation?

IP Geolocation is a mechanism to associate the virtual identity of a device connected to the Internet with its physical address. The virtual identity is represented by the IP (Internet Protocol) address. The physical address is the location point of that device on the earth’s geographical span, represented by latitude and longitude. It can be further extrapolated to the geopolitical or postal address we use daily to identify the location.

This linkage between the IP address and geographical location establishes the identity and facilitates the tracking of devices. These two aspects are important security considerations for safeguarding users in the virtual world.  Identity ensures that the users in the virtual world can trust each other, whereas tracking lets law enforcement agencies find the actual location of the device in case of a mala fide activity perpetrated by the device. But tracking also has some novel uses that we will present later.

Let’s send your first free
IP Geolocation
call
See why the best developers build on Abstract
Get your free api

Basics of IP Geolocation

What is an IP Address?

The IP Address is a form of identification mechanism for the devices communicating over the Internet. IP addresses are defined as part of the IETF (Internet Engineering Task Force)  specifications. All devices connected to the Internet are assigned a unique public IP address. 

How does IP Geolocation Work?

The IP address allocation is governed by Regional Internet Registries (RIR) and Internet Assigned Numbers Authority (IANA). The RIRs are divided into five registries covering the world's major continents and geographical regions, and different IP address series are assigned to these RIRs. Further, under each RIR, multiple Internet Service Providers (ISP) operate locally, covering countries and cities. A subset of the RIR’s IP addresses is allocated to the ISPs.

When a person is connected to the Internet,  their traffic is uniquely identified by their ISP's assigned IP address. Since that IP address is mapped to an RIR and a local ISP, it is possible to predict the person's location. This registry information maintained at RIRs and ISPs is the fundamental basis of IP geolocation. This is just an approximate location, as the precise location cannot be determined based on the registry information. However, ISPs maintain their internal database containing the customers' postal addresses, which can yield more accurate IP geolocation information.

Understanding Geolocation Data

The geolocation IP data mainly contains the latitude and longitude of the location of the Internet subscriber. This information is further augmented with geo-political information identifying the country code, state, province, or city.

Apart from the location-specific information, the geolocation data may also contain the ISP details, timezone, and network or connectivity-related information. 

Getting Started with PHP IP Geolocation

Since most activities in the virtual world happen via websites and web applications, it is obvious that many web servers capture the IP geolocation information of the site visitor's IP address. PHP is one of the most popular programming languages for building web server logic. Therefore, we have restricted our focus to PHP’s way of finding and leveraging IP geolocation. 

For retrieving the IP geolocation of a computer via PHP, it is important to connect to a central database to retrieve IP data that contains the latest IP address registry mappings from RIRs and ISP.

How to retrieve a user's IP address in PHP

The PHP variable $_SERVER is an array whose entries are created by the webserver. It contains information about the server and the HTTP connection, such as HTTP headers and the client's IP address.

The easiest way to get the visitor's IP address is to use the REMOTE_ADDR entry, which returns the client's IP address requesting the current page.


echo `Client IP address: `.$_SERVER[`REMOTE_ADDR`];

But when the webserver is behind a proxy, REMOTE_ADDR will return the proxy's IP address, not the user's. In this case, the proxy would have set the real client's IP address in an HTTP header, generally HTTP_CLIENT_IP or HTTP_X_FORWARDED_FOR. Here is a script that covers most of the cases:


function clientIpAddress(){
if(!empty($_SERVER['HTTP_CLIENT_IP'])){
$address = $_SERVER['HTTP_CLIENT_IP'];
}elseif(!empty($_SERVER['HTTP_X_FORWARDED_FOR'])){
$ address = $_SERVER['HTTP_X_FORWARDED_FOR'];
}else{
$ address = $_SERVER['REMOTE_ADDR'];
}
return $address;
}

echo 'Client IP address: '.clientIpAddress();

How to Geolocate an IP Address in PHP with an API

This is also possible using an API service that maintains such a database. 

Let’s see a quick demo of this operation using the AbstractAPI IP Geolocation API:

1 - Sign up for AbstractAPI's free IP Geolocation API

Signup for a free AbstractAPI account. After that, navigate to the IP Geolocation API page and note the API key. You can also check the documentation to get the API endpoint.

2 - Extract an IP address with the API using the following script

The Geolocation details on an IP address can be extracted by calling this API through a simple PHP script using the cURL library. Here is the complete code for the PHP script:



$GLOBALS['env'] = "production"; // development

if( $GLOBALS['env'] !== "development" )
{
error_reporting(E_ERROR | E_WARNING | E_PARSE);
@ini_set("display_errors", 1);
}
else
{
error_reporting(E_ALL);
@ini_set("display_errors", 0);
}

function get_env()
{
return ($GLOBALS['env'] == 'development') ? true : false;
}

function _is_curl_installed()
{
if(in_array ('curl', get_loaded_extensions())) {
return true;
} else {
return false;
}
}

function init_curl($ip)
{
$response = new stdClass();
$response->status = 0;
$response->error_message = '';
$response->output = '';

$apiPrefix = 'https://ipgeolocation.abstractapi.com/v1/?api_key=';

// check curl extension is enabled or not
if( _is_curl_installed() )
{
$ip_valid = filter_var($ip, FILTER_VALIDATE_IP);
if( $ip_valid )
{
if( get_env() )
{
echo "\n IP address ".$ip." is valid \n";
}
}
else
{
$response->status = 0;
$response->error_message = $ip. " is not a valid IP address.";
$response->output = '';
return $response;
}

// Initialize curl
$ch = curl_init();

// URL for Scraping
curl_setopt($ch, CURLOPT_URL, $apiPrefix.'&ip_address='.$ip);

// set curl options
curl_setopt_array($ch, array(
CURLOPT_URL => $apiPrefix.'&ip_address='.$ip,
CURLOPT_RETURNTRANSFER => true,
CURLOPT_ENCODING => '',
CURLOPT_MAXREDIRS => 10,
CURLOPT_TIMEOUT => 0,
CURLOPT_FOLLOWLOCATION => true,
CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
));

$output = curl_exec($ch);

// get server status code
$httpcode = curl_getinfo($ch, CURLINFO_HTTP_CODE);

if($output === false)
{
if( get_env() )
{
echo "\nCurl error no: " . curl_errno($ch) . "\n";
echo "Curl error: " . curl_error($ch) . "\n";
echo "Curl error description: " . curl_strerror(curl_errno($ch)) . "\n";
}

$response->status = $httpcode;
$response->error_message = curl_strerror(curl_errno($ch));
$response->output = '';
}
else
{
$response->status = $httpcode;
$response->error_message = '';
$response->output = $output;
}
// Closing cURL
curl_close($ch);

return $response;
}
else
{
if( get_env() )
{
echo "\nCurl is not enabled. Please enable curl extension in php.ini.\n";
echo "Change ;extension:curl => extension:curl in your php.ini and try again.\n";
}
$response->status = 0;
$response->error_message = "Curl is not enabled";
$response->output = '';
}
}


// Start

// check arguments
if( $argc == 2 )
{
$ipaddr = $argv[1];
}
else
{
echo "Could not get IP address from command line option\n";

die();
}

// call curl request
$response = init_curl($ipaddr);

// check response for errors.
if( $response->status == 200 )
{
// output the response
echo json_encode(json_decode($response->output), JSON_PRETTY_PRINT);
}
else
{
if( $response->status != 0 )
{
echo "Server HTTP Status : ".$response->status." \n";
}

if( $response->output != "" )
{
echo $response->output;
}
if( $response->error_message != "" )
{
echo "Server Response : ".$response->error_message;
}
}

die();
?>

This code will echo country and other geo-political details associated with the location of an IP address. This code can be copied on a PHP code editor. Before saving it, replace the placeholder <YOUR_API_KEY> with the API key assigned during signup. 

3 - Execute the PHP Script

To execute this PHP script, the following prerequisites are needed:

  1. PHP 8 runtime environment installed on the computer
  2. cURL PHP library is enabled through php.ini config file

The script calls the init_curl( ) PHP function to pass the IP address passed as an argument to a command line terminal to convert API JSON response in a pretty display format.

The above example displays the API response with geolocation details for the IP address 223.34.4.27. It can be seen that this IP address belongs to South Korea, and the other relevant location details like country name and region code can be analyzed further.

The logic within this  PHP script can be ported to a PHP web server to detect the geolocation information of web visitors. 

Another way: Using the free MaxMind IP geolocation tool in PHP

MaxMind offers multiple IP geolocation databases that can be downloaded for free from its website. The 2 main free databases are GeoLite2 Country which allows you to get the country name corresponding to an IP address, and GeoLite2 City to obtain the country, region, and city name. The second is the most accurate but also the largest in terms of file size.

The first steps are to sign-up to the MaxMind website and validate your email address. Then you will be able to download the compressed databases from your account page. You will find the geolocation database in the compressed file, named GeoLite-Country.mmdb or GeoLite2-City.mmdb.

Then you will need to download the API used to query the MaxMind database. For PHP, the officially supported API can be found on GitHub, as well as its documentation.

Installation of GeoIP2 PHP API can be done through Composer. First, install Composer if it’s not already available on your system:


curl -sS https://getcomposer.org/installer | php

Then you can install the API and its dependencies:


php composer.phar require geoip2/geoip2:~2.0

To finally use this API, you must create a new \GeoIp2\Database\Reader object, passing the path to the MaxMind database file downloaded earlier, then you can query it. Here is an example of its usage with the City database:


require_once 'vendor/autoload.php';
use GeoIp2\Database\Reader;

// Creates the API reader object
$reader = new Reader('/path/to/GeoIP2-City.mmdb');

// Get information from the IP address
$address = clientIpAddress();
$record = $reader->city($address);

echo($record->country->name); // 'United States'
echo($record->city->name); // 'Mountain View'
echo($record->location->latitude); // 37.4223
echo($record->location->longitude); // -122.085

Drawbacks of using MaxMind geolocation in PHP

Downloading the MaxMind database and installing its API are additional steps that may put off some of us. Since such a database is updated regularly, you will have to download it again on your servers each time it is updated.

Moreover, the MaxMind files being quite large, you may have a performance loss when several visitors are connected simultaneously on your server.

Best IP Geolocation APIs

There are quite a few IP Geolocation APIs that strive to maintain the most accurate and detailed information about IP address locations. Here is a list of the popular APIs to choose from.

  1. Abstract API: Abstract IP Geolocation API provides highly accurate geolocation data covering 1.75+ million locations across 225,000+ cities worldwide. It offers a freemium subscription starting with 20,000 free API calls per month and $9/month.
  2. MaxMind Geo IP2 - The MaxMind GeoIP2 is a suite of libraries for building IP geolocation applications. It offers intelligent features to detect proxy and anonymous IP addresses to protect enterprise applications accessed by malicious actors.  It is available under a commercial licensing model.
  3. IP2Location: IP2ocation offers many databases containing combinations of IP geolocation data elements classified based on country, city, and further. The data is either available as a direct download or accessible through SDKs. Each classification of IP geolocation data has separate pricing.
  4. GeoPlugin: It is a simple and free geolocation API that provides all the essential information related to IP geolocation. It supports easy integration with client-side JavaScript and server-side.
  5. HostIP: A community-based IP geolocation service with a simple API to retrieve IP geolocation data. It also offers to download its IP geolocation database. It is a totally free service.

Use Cases for IP Geolocation

Beyond the location identification and tracking of devices, IP Geolocation assumes a lot of importance in building intelligent web applications for achieving advanced capabilities such as:

  1. Location-specific customization in web applications: Visitors accessing the Internet from specific locations are served geotargeted content, such as local adverts, and displayed in the local language.
  2. Location-based filtering: Applications hosted for specific geographic locations can use geolocation data to allow or deny access to visitors based on their geolocation data.
  3. Cyber security Enhancement: IP Geolocation information serves to aid in cybersecurity-related scrutinies to detect fraudulent activities performed by users and tag their IP addresses and locations for further analysis.

Tips and Tricks for IP Geolocation

Accessing IP Geolocation is quite simple, but working with this data entails some responsibilities to ensure optimal performance and data usage. Here are some tips and tricks to remember while incorporating IP geolocation in a web application:

  1. Optimizing Geolocation Performance: It is possible to cache and build a separate local database of IP geolocation data from the APIs. This helps optimize the IP geolocation queries and saves costs in API calls. 
  2. Handling errors in geolocation data: Geolocation data may be prone to errors depending on the API service tiers and the data quality captured by the data providers. Usually, free or community services will be prone to errors or incomplete information. To avoid issues related to IP geolocation in production-grade applications, paying subscriptions for two API services, one as primary and the other as a backup service, is advisable for fetching IP geolocation details. 
  3. Legal use of IP Geolocation data: Applications using IP geolocation must adhere to the terms of use policies of the APIs and database providers. Further, some laws and jurisdictions consider the IP address as Personally Identifiable Information (PII). Therefore, application providers should do their due diligence if they plan to cache for store the IP addresses themselves. 
  4. Managing risks associated with IP geolocation data capture: IP geolocation data is approximate information. It can never pinpoint the exact location of the user’s computer. Moreover, in mobile internet access, the user’s location changes constantly. Therefore, using this information only to capture the broader geo-political information is advisable. 

Future of IP Geolocation: 

IP geolocation data is based on broader regions and geo-political identities. This is mostly static geolocation data and only changes sometimes. However, it doesn’t address some of the more modern usage scenarios. As a result, there is a need to enhance geolocation data accuracy.

One of the ways to achieve a more accurate geolocation data capture is to rely on GPS systems. This is all the more applicable for mobile devices, as all modern smartphones have a built-in GPS mechanism.  With the help of GPS, it is possible to build location-aware applications, which is otherwise impossible using the IP geolocation data available from APIs and database services. One example is a location-based reminder service, wherein a mobile app tracks the user's movement and raises an alert when the user’s phone is near a preset location. 

IP geolocation also assumes more importance in the current scenario, where many AI agents and chatbots are available online. These virtual beings are constantly interacting with human beings. In such cases, capturing the IP geolocation data of computers hosting these virtual entities is important to safeguard humans in cyberspace.

Conclusion

IP geolocation continues to be an integral part of Internet operations. With technological advancements and more complex usage scenarios, geolocation-capturing techniques have evolved. 

For capturing the broader geographical details of an IP address, it is good to rely on a credible API for fetching geolocation data. Geo-location capture must be done for mobile applications using GPS or A-GPS technology. However, it must be noted that capturing the geolocation through GPS is not considered a true IP geolocation technique since the GPS system does not use the IP address to find the location of the device. But for building a custom location-based application, it might be worthwhile to map the device’s IP address with GPS-captured location data to build a location-centric profile of the device for specific use cases. 

FAQs

What is IP Geolocation, and why is it important?

IP geolocation is mapping an IP address to a geographical location. This mapping is done at the regional internet registry level, and further allocated at the internet service provider level, to assign IP addresses to individual internet subscribers. The IP geolocation data contains the latitude and longitude point of the IP address, the geo-political information, and ISP and connectivity details. There are many credible data sources of this information, which are offered as APIs or databases. AbstractAPI IP Geolocation API is one service that can fetch IP geolocation data from ISPs and other data providers.

How does PHP IP Geolocation work?

Every client application that sends a request to the PHP server backend also passes the client’s IP address. The PHP backend can leverage one of the Geolocation APIs or SDKs to get the geolocation data. Using the cURL library, it is possible to make an API call to an IP geolocation service to get the geolocation details for further processing. AbstractAPI is one of the most reliable services for providing IP geolocation data, from across 225,000 cities around the world.

Which PHP Geolocation library is best?

If you are looking for a simple REST API with reliable IP geolocation data, you can choose AbstractAPI IP Geolocation API, which supports IPv4 and IPv6 addresses. If you are looking for more detailed information on anonymous IP addresses or additional intelligence about the IP addresses, then you can opt for MaxMind GeoIP service. For free API access or community-supported IP address databases, you can choose between GeoPlugin or Host IP service.

Shyam Purkayastha

Shyam Purkayastha is a proficient web developer and PHP maestro, renowned for his expertise in API creation and integration. His deep knowledge of PHP scripting and backend development enables him to build scalable server-side applications. Shyam is particularly passionate about RESTful API design, significantly enhancing web service functionality and data interoperability.

Get your free
IP Geolocation
key now
See why the best developers build on Abstract
get started for free

Related Articles

Get your free
IP Geolocation
key now
4.8 from 1,863 votes
See why the best developers build on Abstract
Thank you! Your submission has been received!
Oops! Something went wrong while submitting the form.
No credit card required