Guides
Last updated
September 7, 2022

Getting IP Geolocation Information in PHP using the CodeIgniter Framework

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

The IP Address is the bedrock of all communication over the Internet. Your real IP address provides a unique internet protocol address mechanism to identify your computer on the Internet. Additionally, it also aids in routing the data and messages from your computer to another remote address attached to a computer with whom you want to communicate over the Internet. However, every valid IP address also contains some interesting information.

Geolocation information is one of the essential information associated with an IP address. IP Geolocation tracking is used to identify the computer's geographic location assigned to the user's IP address. If you want to find your computer's correct IP address and geolocation details, you can visit https://whatismyipaddress.com/.

Some key information elements within the IP geolocation data are the city, region, country names, and approximate latitude and longitude points. You can test this website with multiple IP addresses to see all the details about different IP addresses.

At Abstract, we offer a comprehensive IP Geolocation database via the Abstract IP Geolocation API. This article will show you how to use this API to build a cloned webpage for https://whatismyipaddress.com/  using the PHP CodeIgniter framework. Let’s dive into this tutorial to build the clone as per this webpage structure. 

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

Abstract's IP Geolocation API comes with libraries, code snippets, guides, and more.Overview of Abstract IP Geolocation API

Abstract IP Geolocation API is a super fast and secure API to get the location-specific information of any IP address.

Apart from the location, this API can fetch ISP details and additional information, such as currency, timezone, and connection type.

How to access IP Geolocation API?

Open an account with Abstract and choose a subscription plan for the IP Geolocation API. You can choose the free plan for now, but note that the free plan has a limit of only 20,000 requests per month.

After successful signup, login to your dashboard and navigate to the IP Geolocation API. Make a note of your private API key.

How to use the IP Geolocation API?

Let's make a simple request using Postman to the IP Geolocation API endpoint.

This example is an API request for an arbitrary visitor IP address 196.50.6.225. The response indicates that the geolocation of this IP address lies in Lagos, Nigeria. The complete API response is somewhat like this.


{
"ip_address": "196.50.6.225",
"city": "Lagos",
"city_geoname_id": 2332459,
"region": "Lagos",
"region_iso_code": "LA",
"region_geoname_id": 2332453,
"postal_code": null,
"country": "Nigeria",
"country_code": "NG",
"country_geoname_id": 2328926,
"country_is_eu": false,
"continent": "Africa",
"continent_code": "AF",
"continent_geoname_id": 6255146,
"longitude": 3.3903,
"latitude": 6.4474,
"security": {
"is_vpn": false
},
"timezone": {
"name": "Africa/Lagos",
"abbreviation": "WAT",
"gmt_offset": 1,
"current_time": "11:58:29",
"is_dst": false
},
"flag": {
"emoji": "🇳🇬",
"unicode": "U+1F1F3 U+1F1EC",
"png": "https://static.abstractapi.com/country-flags/NG_flag.png",
"svg": "https://static.abstractapi.com/country-flags/NG_flag.svg"
},
"currency": {
"currency_name": "Naira",
"currency_code": "NGN"
},
"connection": {
"autonomous_system_number": 37682,
"autonomous_system_organization": "TIZETI-AS",
"connection_type": "Corporate",
"isp_name": "Tizeti Network Limited",
"organization_name": "Customer Snet3"
}
}

Most of the information in this response is self-explanatory. However, you can check the API documentation from your logged account on Abstract for a complete guide on the API response and its meaning.

Building the WhatIsMyIP Website Clone with PHP/CodeIgniter and Abstract IPGeolocation API

CodeIgniter is a robust PHP framework with a minimal footprint, built for developers who need a simple and elegant toolkit to create full-featured web applications. It is one of the earlier frameworks and has been around since 2011.

Some of the salient features of CodeIgniter include:

  • Model-View-Controller Based System
  • Extremely Light Weight
  • Full Featured database classes with support for several platforms.
  • Query Builder Database Support
  • Form and Data Validation
  • Security and XSS Filtering

We will leverage CodeIgniter to build the WhatIsMyIp clone webpage, a minimal replica of the https://whatismyipaddress.com/ webpage.

To follow the steps in this tutorial, you are expected to be familiar with HTML and PHP. Additionally, awareness or working knowledge of CodeIgniter would be an advantage.

Prerequisites for Project Setup

Create a separate directory that will act as the root project directory for all the project files and dependencies.

Additionally, make sure that you have a development environment that supports PHP with 

  • PHP 7.3 or newer
  • Recent versions of CodeIgniter4 installed. You can refer to the installation guide to ensure that the CodeIgniter library is installed correctly and tested within the root project directory. 
  • VS Code, or any PHP-compatible IDE
  • Google Maps JavaScript API Key for displaying the geolocation on maps.

Coding Steps

Before proceeding, ensure that your default CodeIgniter development server works so that you can see the welcome page on the browser.

Follow the steps below to modify the default welcome page PHP script and the Home controller PHP script in the CodeIgniter framework code.

Step 1: Update the HTML Webpage snipper for WhatIsMyIP clone

At first, you have to add the HTML/JavaScript code that gets served to the browser.

Open the file ‘app/Views/welcome_message.php’.

Replace the entire content of this file with the code snippet below.







WhatIsMyIp Clone























$status ?
'

My IP Address is:



IPv4:

' . $ipv4 . '




IPv6:

'.$ipv6. '




My IP Information:



ISP:
' . $isp_name . '



City:
' . $isp_city . '



Region:
' . $isp_region . '



Country:
' . $isp_country . '









'
:
'

Could not find your IP Address.

'
?>











This code is a simple Bootstrap-based web page that displays a panel with the IP geolocation details and the pin on the map. This webpage somewhat mimics the https://whatismyipaddress.com/ homepage, as we saw earlier.

Before saving this file, ensure that you replace the placeholder <YOUR-GOOGLE_MAP_KEY> with your Google Maps JavaScript API key.

Step 2: Update the Home Controller

Locate the file ‘app/Controllers/Home.php’.

Replace the entire code with the below code snippet.



namespace App\Controllers;

class Home extends BaseController
{
public function index()
{

try {
// build required data
$formData = http_build_query([
'api_key' => '',
'ip_address' => $this->request->getIPAddress()
]);
// make curl request to abstractapi.com to get ip information
$curl = curl_init();
curl_setopt_array($curl, array(
CURLOPT_URL => "https://ipgeolocation.abstractapi.com/v1/?" . $formData,
CURLOPT_RETURNTRANSFER => true,
CURLOPT_ENCODING => "",
CURLOPT_MAXREDIRS => 10,
CURLOPT_TIMEOUT => 30,
CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
CURLOPT_CUSTOMREQUEST => "GET",
CURLOPT_HTTPHEADER => array(
"accept: application/json",
"cache-control: no-cache",
"content-type: application/json",
),
));
$response = curl_exec($curl);
$err = curl_error($curl);
curl_close($curl);
if ($err) {
$data = [
'status' => false,
'message' => $err
];
} else {
$response = json_decode($response, true);
$data = [
'status' => true,
'ipv4' => $response['ip_address'] ?? '',
'ipv6' => $this->request->getIPAddress() ?? '',
'isp_name' => $response['connection']['isp_name'] ?? 'Unknown',
'isp_city' => $response['city'] ?? 'Unknown',
'isp_region' => $response['region'] ?? 'Unknown',
'isp_country' => $response['country'] ?? 'Unknown',
'isp_lat' => $response['latitude'] ?? 0,
'isp_lng' => $response['longitude'] ?? 0,
];
}
return view('welcome_message', $data);
} catch (\Exception $e) {
exit($e->getMessage());
}


}

}

This controller calls the Abstract IP Geolocation API to fetch the specific information displayed on the webpage. The IP address is passed from the request coming from the browser. In addition, this controller extracts the ISP's name and location information, including latitude and longitude, to be displayed on the map.

Before saving this file, ensure that the placeholder <YOUR_ABSTRACT_API_KEY> is replaced with the actual private key as per your Abstract account.

Step 3: Test the Webpage

Now, you can test the webpage. 

Assuming that the PHP development server is running, you can refresh or open http://localhost:8080 and see the WhatIsMyIP clone webpage.

You can see that the webpage has been rendered in a certain structure which is in line with the original https://whatismyipaddress.com/ website. However, there is no data captured related to the IP address or its geolocation.

This problem happens because the controlled code expects the IP address to be passed from the HTTP request.


'ip_address' => $this->request->getIPAddress()

On a local development server, the IP address is 127.0.0.1. This address is a loopback user IP address, not a public IP address routable over the Internet. Therefore, it is considered an invalid IP address that cannot have associated geolocation information.

To circumvent this problem, you can host the CodeIgniter application on a cloud server, such as the AWS EC2 instance, or GCP Compute engine. In that case, the captured client IP address in PHP code will reflect the actual IP address of the computer.

Another alternative is a quick hack within the code to test the IP Geolocation information displayed on this WhatIsMyIp clone webpage.

To achieve that, replace the line


'ip_address' => $this->request->getIPAddress()

with


'ip_address' => '170.44.67.3'

We have taken an arbitrary IP address, 170.44.67.3, but you can also choose any IP address which has the correct format and is not reserved or within a private network range.

Refresh the WhatIsMyIp clown page now to check the outcome.

As you can see, the IP address is now captured, and its location coordinates and ISP details are also displayed, thanks to the Abstract IP Geolocation API.

Try using some other IP addresses, and you should be able to get their details on this page.

Conclusion

Using PHP CodeIgniter, you have learned how to leverage Abstract IP Geolocation API on a simple web app. As a next step, you can beautify the current page presentation to display more information, such as timezone, flag, and connection type associated with the IP address. 

Go ahead and give it a shot. We can't wait to see the incredible things you can build with the Abstract APIs.

FAQs

How Can You Get IP Address Details using CodeIgniter?

In CodeIgniter, you can get the IP address of the incoming HTTP request using the getIPAddress( ) function. You can also get geolocation-related information about the IP address by calling the Abstract IP Geolocation API via the PHP curl library. This API provides additional information about the IP address, such as the location coordinates, geolocation information, time zones, and ISP details.

What information can be extracted from an IP address?

An IP address is associated with the geographical location of the ISP, which is allocated the said IP address. Therefore, the IP address contains geolocation information and other secondary information related to geolocation. With Abstract IP Geolocation API, you can retrieve the primary location information of the IP address. Additionally, you can also retrieve information about the city, region, and country, along with timezone and connection type.

What is the use of IP Geolocation?

IP geolocation refers to the geographical information associated with a public IP address. It primarily contains latitude and longitude coordinates of the IP address, along with the Internet Service Provider (ISP) details. All this information is valuable in profiling Internet users for different use cases, such as localization, targeted outreach, and law enforcement.

Shyam Purkayastha
Get your free
IP Geolocation
key now
This is some text inside of a div block.
get started for free

Related Articles

Get your free
key now
IP Geolocation
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