IP Address Lookup using Abstract API and PHP

While working on applications, you might want to get the geolocation of a user. Based on a user’s geolocation, different content can be served on the website. It might be different prices, advertisements, offers, etc.

In this article, we discuss one IP address lookup tool called Abstract IP geolocation API. We will study how to integrate Abstract’s API in the web application. They provide an API to interact with their service and receive the geolocation of users.

I am going to use PHP cURL, Guzzle, and vanilla JavaScript to interact with Abstract’s API.

Get Abstract API Key

To get started, you first need to register with the Abstract IP Geolocation API. They provide both free and premium plans. In the free plan, at the time of writing this article 20000 requests per month are allowed. However, you can pick the plan as per your requirement.

Upon registration, you will get access to the dashboard. From the dashboard, copy the API key which will be required while calling their API.

Get IP Address of a User

You are ready with the API key. Next, we need to find out the user’s IP dynamically. You probably thought that using $_SERVER['REMOTE_ADDR'] one can get the IP address directly. This is not true if the server is located behind the proxy or firewall. We can handle such cases using the code below.

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

In the above code, I added checks for HTTP_CLIENT_IP and HTTP_X_FORWARDED_FOR. These 2 variables give the user’s IP address from the servers using proxy or firewall. If both of these values are not found then we get an IP address using REMOTE_ADDR.

IP Address Lookup using Abstract API

It’s time to go ahead and interact with Abstract’s IP geolocation API. Let’s first start with the PHP cURL. In order to use cURL, make sure the cURL extension is enabled on your server.

$ip_address = getUserIpAddr();
$api_key = 'API_KEY';
$url = "https://ipgeolocation.abstractapi.com/v1/?api_key=$api_key&ip_address=$ip_address";
$ch = curl_init();  
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_URL, $url);
$response = curl_exec($ch);
if (curl_errno($ch)) {
    $error_msg = curl_error($ch);
    echo $error_msg;
}
$arr_result = json_decode($response, true);
print_r($arr_result);

Make sure to replace the placeholder API_KEY with the actual value. Upon running this code, you will get details like city, country, timezone, latitude and longitude, and much more. The output is something like below.

Array
(
    [ip_address] => 103.47.153.189
    [city] => Pune
    [city_geoname_id] => 1259229
    [region] => Maharashtra
    [region_iso_code] => MH
    [region_geoname_id] => 1264418
    [postal_code] => 411038
    [country] => India
    [country_code] => IN
    [country_geoname_id] => 1269750
    [country_is_eu] => 
    [continent] => Asia
    [continent_code] => AS
    [continent_geoname_id] => 6255147
    [longitude] => 73.7286
    [latitude] => 18.6161
    [security] => Array
        (
            [is_vpn] => 
        )

    [timezone] => Array
        (
            [name] => Asia/Kolkata
            [abbreviation] => IST
            [gmt_offset] => 5
            [current_time] => 16:11:33
            [is_dst] => 
        )

    [flag] => Array
        (
            [emoji] => IN
            [unicode] => U+1F1EE U+1F1F3
            [png] => https://static.abstractapi.com/country-flags/IN_flag.png
            [svg] => https://static.abstractapi.com/country-flags/IN_flag.svg
        )

    [currency] => Array
        (
            [currency_name] => Indian Rupee
            [currency_code] => INR
        )

    [connection] => Array
        (
            [autonomous_system_number] => 134006
            [autonomous_system_organization] => Sheng Li Telecom India Private Limited
            [connection_type] => Corporate
            [isp_name] => Sheng Li Telecom India Private Limited
            [organization_name] => Sheng Li Telecom India Private Limited
        )

)

One may not want all this information. You can limit the response by passing the fields parameter. Let’s say you want to get only city and country. Then build the URL as follows.

$url = "https://ipgeolocation.abstractapi.com/v1/?api_key=$api_key&ip_address=$ip_address&fields=city,country";

On your website, you probably get some visitors who are using VPN. The VPN makes it difficult to find the actual IP address of a user. The IP address you get from the server is the VPN’s and not the visitors. In the response of Abstract API, it also gives the value of VPN using $arr_result['security']['is_vpn']. If this value is not empty, it means the visitor is using VPN and there is no way to get their original IP address.

Using Guzzle

In the case of PHP frameworks like Laravel or others you probably want to use Guzzle. The Guzzle is a PHP HTTP client for sending HTTP requests and receives an HTTP response. It is an alternative to PHP cURL.

To use the Guzzle, install it using the below command.

composer require guzzlehttp/guzzle

After this, write the code below which gives a call to Abstract API via the Guzzle library.

<?php
require_once "vendor/autoload.php";
 
use GuzzleHttp\Client;
 
$ip_address = getUserIpAddr();
$api_key = 'API_KEY';

try {
    $client = new Client([
        // Base URI is used with relative requests
        "base_uri" => "https://ipgeolocation.abstractapi.com",
    ]);
      
    $response = $client->request("GET", "/v1/", [
        "query" => [
            "api_key" => $api_key,
            "ip_address" => $ip_address,
        ]
    ]);
      
    //get status code using $response->getStatusCode();
 
    $body = $response->getBody();
    $arr_result = json_decode($body, true);
    print_r($arr_result);
} catch(Exception $e) {
    echo $e->getMessage();
}

Using JavaScript

Like PHP, you can even interact with Abstract API using JavaScript. Most probably in JavaScript framework, you might need it.

var ip_address = 'IP_ADDRESS';
var api_key = 'API_KEY';

fetch('https://ipgeolocation.abstractapi.com/v1/?api_key='+api_key+'&ip_address='+ip_address)
.then(response => response.json())
.then(data => {
    console.log(data);
});

Conclusion

Finding geolocation by IP address is essential in certain scenarios. We studied how to use the IP address lookup tool called Abstract API to get the geolocation information of a visitor. We covered both PHP and JavaScript code for interacting with their API. It will help users to find the best suitable option for their project.

If you liked this article, then please subscribe to our YouTube Channel for video tutorials.

Leave a Reply

Your email address will not be published. Required fields are marked *