Guides
Last updated
November 6, 2024

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

Knowing a user’s location has a wide range of applications, most of them aimed at improving those users’ experiences, analyzing geographic data for business insights, and enhancing security measures. With this in mind, it is quite logical to wonder whether is it possible to find the exact location of an IP address, and how to extract it in PHP. 

We have good news for you: it is possible to get accurate location data from an IP address… And it’s quite simple, to be honest. Especially, when using PHP and a geolocation API to retrieve the data.

In this guide, we’ll show you how to extract the location of an IP address, including country, city, and region, using simple PHP code with the help of an API, so that you can fully exploit the possibilities IP geolocation holds.

Already know some of it? Jump straight to the tutorial on how to geolocate an IP address with PHP. If not, let’s start with the basics.

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

IP Geolocation 101

IP Geolocation is a mechanism to associate the virtual identity of a device connected to the Internet with its physical address. In other words, the approximate location point of that device on the earth’s geographical span (i.e., its coordinates). 

The virtual identity, on the other hand, is represented by the IP (Internet Protocol) address of the device.  All devices connected to the Internet are assigned a unique public IP address, based on the network they are connected to.

This linkage between the IP address and geographical location helps track devices and establish their identity. Therefore, geolocation is crucial for enforcing security measures (like fraud detection), as well as for tracking a user’s actions and delivering geo-specific content to meet particular needs.

To sum up: IP geolocation enables you to link a user’s IP address to their location. Therefore, to determine a location from an IP address, you will first have to geolocate it. One of the most effective and accurate methods for doing this is by using a geolocation API.

Getting Started with PHP IP Geolocation

IP geolocation provides you with a unique all-in-one opportunity to strengthen your software’s security, enhance your marketing and commercial insights, and improve the user experience. 

To retrieve this data using a geolocation API, you’ll need to make a request through a code script. 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.

The whole process of geolocating an IP address in PHP can be broken down into three major stages

  1. Identifying the user’s IP address.
  2. Geolocating it ―using a geolocation API.
  3. Extracting the location data (e.g., country, city) from the API response.

Let’s address each one of them, step by step.

How to Geolocate an IP Address in PHP with an API

First of all, to get an IP address geolocation using an API, you’ll have to register for the API service and obtain your API key. This is required for authentication purposes.

  1. Once you have your account, you’ll have to get the visitor's IP address. To do so, use the $_SERVER['REMOTE_ADDR'] entry, which returns the user’s IP address. This is due to the  $_SERVER array containing information about each request a user makes to your server. The variable $_SERVER['REMOTE_ADDR'] holds, specifically, that users’ public IP.
  2. Afterward, you’ll need to make a GET request to the API using PHP.  For this, you can use file_get_contents() or cURL. The API will retrieve the IP address location data and return it to you as a JSON response.
  3. Convert the JSON string into a PHP data structure (either an array or an object) by using json_decode(). Then, extract specific data values using the appropriate keys.

How Do I Extract the Location from an IP Address?

For the sake of clarification, let’s break down in detail this process, using the following code snippet to exemplify. 

When writing a GET request in PHP for a geolocation API, there are a few steps you have to follow.

  1. To map a user’s location, you’ll first need their IP address. To retrieve it, you can use the $_SERVER['REMOTE_ADDR'] entry either on its own or as a part of a broader request.
  2. Then, you’ll have to write down the GET HTTP request using PHP. This consists of:some text
    1. The API request URL, which includes your API key (for verification) and the user’s IP.
    2. The file_get_contents() entry. This will instruct the software to send the request and get the response.
    3. The json_decode() entry, to convert the JSON response into a PHP array.

Typically, the API’s response will contain details such as the user’s region, city, and country. Depending on the API, you’ll be able to get additional data, like whether the user is requesting a VPN and ISP (Internet Service Provider) information. 

Converting the JSON response into PHP should allow you to extract it, as long as you reference the specific keys correctly. After doing so, you’ll get an output from the API. That is, the processed result is based on the extracted values. It should look like this for a NYC-based user: 

In this example, the key $locationData['country'] returns "United States", while the key $locationData['city'] returns "New York".

Can I Find the Location of an IP Address?

IP geolocation services allow you to retrieve an IP address geolocation. Though the results tend to be accurate they are not 100% precise. Typically, the accuracy levels of IP-based geolocation are

  • 99%-95% when mapping countries.
  • 80%-55% for identifying a region (state) within.
  • 75%-55% if you intend to retrieve the user’s city.

The truth is that IP geolocation has its limits since it relies on publicly available information about how IP addresses are distributed by ISPs. Consequently, some factors that may hinder its accuracy are:

  • VPN and Proxies usage. Accessing a website or app by Proxy or VPN masks the user’s real IP. Because of this, the retrieved location data will be inaccurate. This can also be achieved using a Tor network.
  • Dynamic and Shared IPs. These IP types pose a challenge to most IP geolocation service providers. Dynamic IPs, for example, frequently change, which makes them harder to track with precision. Corporate and shared IPS, for their part, prevent the mapping of individual users.
  • Databases. Most geolocation APIs use external databases for identifying a user’s location. This means that their accuracy depends, directly, on how often are those databases updated. The more often, the better, in terms of the result’s precision.

Furthermore, IP addresses tend to be registered to ISP companies. Therefore, sometimes its location will be that of the ISP registered office, instead of the user’s actual location.

If IP geolocation does not fulfill your software’s needs, you may want to consider alternative geolocation methods, such as browser or GPS-based geolocation. This is all the more applicable for mobile devices, as all modern smartphones have a built-in GPS mechanism.  

While this method often renders more accurate results than IP geolocation it has one downside: the user must accept to share their location for you to track it. Another option is 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. 

Finally, 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. 

Can You Get Location Data from IP Address?

As we briefly mentioned, the information an IP address conveys goes beyond the mere location of the user. When using a geolocation API you can even customize the data that will be retrieved from the IP address. 

Nevertheless, on a general basis, the location data that IP geolocation displays are:

  • The country where the IP address is either registered or currently located. 
  • The region within a country where the user’s network can be located. 
  • The city or locality linked to the IP address.
  • The device’s geographic coordinates. That is, its latitude and longitude.
  • The IPS manages the network infrastructure that connects the user to the internet.

This is useful when due to licensing agreements, censorship, or legal regulations the content and services of a site need to be tailored for a specific country or region. 

By identifying a user’s location you can redirect them to the appropriate interface or even block their requests. It is also helpful for e-commerce that showcases different prices for different locations due, for example, to varying tax rates or shipment costs. 

IP address data can be further used for location-based advertising. For example, by knowing a user’s city a website may push promotions for an oncoming local event… As well as for nearby stores if it can access the user’s coordinates.

On the contrary, the main functions of identifying a user’s ISP are security-related. If a user request originates displays an unknown ISP, it may be considered suspicious. Still, ISP data can also provide insights into which ISPs are popular in certain regions by analyzing user demographics.

Geolocating an IP Address in 3, 2, 1

Let’s go over the drill one more time. Mapping a user with data from their IP address is a simple, straightforward procedure. Especially, when it is done using geolocation tools. 

Mainly, it involves three steps: (1) retrieving the user’s IP, (2) calling a geolocation API, and (3) extracting the necessary data. While the data is usually accurate, factors like VPNs or the database employed can affect the precision of IP geolocation.

This doesn’t mean, though, that IP geolocation isn’t useful. It serves various purposes, ranging from security enforcement to local-oriented marketing and user demographics analysis.

Profiting from the advantages of IP geolocation also involves a simple, straightforward procedure: it begins with you signing up for a free trial with Abstract API today 😉

Who said improving your products with IP geolocation wasn’t easy? You know what to do, it’s time to give it a try.

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. 

It can be used to enhance security measures by detecting and blocking suspicious user requests. Other functions encompass demographics analysis and local-oriented marketing campaigns.

IP geolocation data contains the IP address coordinates, geo-political information, and ISP and connectivity details. 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?

PHP IP geolocation leverages external databases to convert IP addresses into useful location data. 

Every client application that sends a request to the PHP server backend also passes the client’s IP address. A PHP backend makes a geolocation API or SKD to get the IP 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.

Quality geolocation APIs, like Abstract API, can provide accurate, consistent results, from across 225,000 cities around the world.

Which PHP Geolocation library is best?

There are quite a few IP Geolocation APIs that strive to maintain the most accurate and detailed libraries on IP address locations. Here are our top three to choose from.

  1. Abstract API: Provides highly accurate geolocation data covering 1.75+ million locations across 225,000+ cities worldwide.
  2. MaxMind Geo IP2: It is a suite of libraries for building IP geolocation applications. It offers intelligent features to detect proxy and anonymous IP addresses.
  3. IP2Location: This software 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.
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