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. 

Don't reinvent the wheel.
Abstract's APIs are production-ready now.

Abstract's suite of API's are built to save you time. You don't need to be an expert in email validation, IP geolocation, etc. Just focus on writing code that's actually valuable for your app or business, and we'll handle the rest.

Get started for free

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.


<!DOCTYPE html>
<html lang="en">
 
<head>
    <meta charset="UTF-8">
    <title>WhatIsMyIp Clone</title>
    <meta name="description" content="The small framework with powerful features">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <link rel="shortcut icon" type="image/png" href="/favicon.ico" />
    <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap@4.6.2/dist/css/bootstrap.min.css" integrity="sha384-xOolHFLEh07PJGoPkLv1IbcEPTNtaed2xpHsD9ESMhqIYd0nLMwNLD69Npy4HI+N" crossorigin="anonymous">
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/css/font-awesome.min.css" integrity="sha512-SfTiTlX6kk+qitfevl/7LibUOeJWlt9rbyDn92a1DqWOw9vWG2MFoays0sgObmWazO5BQPiFucnnEAjpAB+/Sw==" crossorigin="anonymous" referrerpolicy="no-referrer" />
 
    <!-- STYLES -->
 
    <style {csp-style-nonce}>
        * {
            transition: background-color 300ms ease, color 300ms ease;
        }
 
        *:focus {
            background-color: rgba(221, 72, 20, .2);
            outline: none;
        }
 
        .info {
            background-color: #1F4872;
            color: white;
        }
 
        .info #p-text {
            font-size: 25px;
        }
 
        .ip-address {
            font-size: 25px;
            border: #2E587F 1px solid;
            background-color: #2E587F;
            padding: 20px;
        }
 
        .isp-address {
            font-size: 20px;
            border: #2E587F 1px solid;
            background-color: #2E587F;
            padding: 20px;
        }
    </style>
</head>
 
<body>
 
    <!-- HEADER: MENU + HEROE SECTION -->
    <header>
        <nav class="navbar navbar-expand-lg navbar-light bg-light">
            <div class="container">
                <a class="navbar-brand font-weight-bold" href="#">WhatIsMyIP Clone</a>
                <button class="navbar-toggler" type="button" data-toggle="collapse" data-target="#navbarSupportedContent" aria-controls="navbarSupportedContent" aria-expanded="false" aria-label="Toggle navigation">
                    <span class="navbar-toggler-icon"></span>
                </button>
            </div>
        </nav>
    </header>
 
    <!-- CONTENT -->
 
    <section>
        <div class="container">
            <div class="row info mt-5 p-5 rounded">
                <?=
                $status ?
                '<div class="col-md-8">
                    <p id="p-text">My IP Address is:</p>
                    <p class="ip-address">
                        IPv4:
                        <span class="fa fa-question" data-toggle="tooltip" data-html="true" title="The most common IP version assigned by ISPs."></span>
                        <span id="ipv4">' . $ipv4 . '</span>
                    </p>
 
                    <p class="ip-address">
                        IPv6:
                        <span class="fa fa-question" data-toggle="tooltip" data-html="true" title="The IP version assigned by routers and other devices that do not support IPv4."></span>
                        <span id="ipv6"> '.$ipv6. '</span>
                    </p>
 
                    <p class="mt-6">
                    <p id="p-text">My IP Information:</p>
                    <p class="isp-address">
                        ISP:
                        <span id="ipv4"> ' . $isp_name . ' </span> <br><br>
 
                        City:
                        <span id="ipv4">' . $isp_city . ' </span> <br><br>
 
                        Region:
                        <span id="ipv4">' . $isp_region . '</span> <br><br>
 
                        Country:
                        <span id="ipv4">' . $isp_country . ' </span>
 
                    </p>
 
                    </p>
 
                </div>
                <div class="col-md-4">
                    <div style="height: 253px;" id="map">
                    </div>
                </div>'
                :
                '<p> Could not find your IP Address. </p>'
                ?>
            </div>
        </div>
    </section>
 
    <script src="https://cdn.jsdelivr.net/npm/jquery@3.5.1/dist/jquery.slim.min.js" integrity="sha384-DfXdz2htPH0lsSSs5nCTpuj/zy4C+OGpamoFVy38MVBnE+IbbVYUew+OrCXaRkfj" crossorigin="anonymous"></script>
    <script src="https://cdn.jsdelivr.net/npm/bootstrap@4.6.2/dist/js/bootstrap.bundle.min.js" integrity="sha384-Fy6S3B9q64WdZWQUiU+q4/2Lc9npb8tCaSX9FK7E8HnRr0Jz8D6OP9dO5Vg3Q9ct" crossorigin="anonymous"></script>
    <script>
        $(document).ready(function() {
            $(function() {
                $('[data-toggle="tooltip"]').tooltip()
            })
        });
 
        function initMap() {
            const myLatLng = {
                lat: <?= $isp_lat ?>,
                lng: <?= $isp_lng ?>
            };
            const map = new google.maps.Map(document.getElementById("map"), {
                zoom: 5,
                center: myLatLng,
            });
 
            new google.maps.Marker({
                position: myLatLng,
                map,
                title: "My Location",
            });
        }
 
        window.initMap = initMap;
    </script>
    <script src="https://maps.googleapis.com/maps/api/js?key=<YOUR_GOOGLE_MAP_KEY>&callback=initMap&v=weekly"></script>
</body>
 
</html>

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.


<?php
 
namespace App\Controllers;
 
class Home extends BaseController
{
    public function index()
    {
       
        try {
            // build required data
            $formData = http_build_query([
                'api_key' => '<YOUR_ABSTRACT_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.

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

Get started for free
Abstract's IP Geolocation API comes with libraries, code snippets, guides, and more.
Get started