Guides
Last Updated Aug 02, 2023

How to Extract Country Name and Related Information from IP Address using PHP

Shyam Purkayastha

Table of Contents:

Get your free
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
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 Internet is like a street lined with shops and businesses. But unlike brick-and-mortar shops with a fixed physical presence on a local street, the ones on the Internet crop up on a virtual broadway, globally connecting all the countries worldwide.

That's why any serious online business would want to track the visitor's location from where visitors are landing on its website. Fortunately, this is easily achieved with an IP address. This article will guide you through several possibilities for extracting country and related information from the IP address by leveraging a free geolocation API with PHP.

Getting Country Name from IPv4 IP Address

IPv4 is still the dominant format of IP addressing used across the world. Therefore, most visitor's IP address logs on web servers will still have this familiar format, with four numbers separated by three dots. 

Let's write a simple PHP code to parse an IP v4 address to extract the country name. For this to work, you must have a PHP development environment with the latest PHP8 version. Additionally, you should also subscribe to Abstract API IP Geolocation API.

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

Once you subscribe, you will get access to the API dashboard with your API key.

Make a note of this API key.

You can use the built-in curl library to call the IP geolocation API within the PHP script. Here is the complete PHP program.


<?php

class IPV4
{

    public function handle(array $request)
    {
        $data = $this->parse_argv($request);
        try {
            // build required data
            $formData = http_build_query([
                'api_key' => '<YOUR_UNIQUE_API_KEY>',
                'ip_address' => $data[0]  
            ]);
            // 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) {
                echo $err;
                exit;
            } else {
                $response = json_decode($response, true);
                echo 'Country: '.$response["country"];
                exit;
            }
        } catch (\Exception $e) {
            echo $e->getMessage();
            exit;
        }
    }


    private function parse_argv(array $argv): array
    {

        $request = [];
        foreach ($argv as $i => $a) {
         
            if (!$i) {
                continue;
            }   

            $isValid = filter_var($a, FILTER_VALIDATE_IP, FILTER_FLAG_IPV4);

            if($isValid) {
                array_push($request,$a);
            } else {
                echo "Invalid IPv4 Format";
                exit;
            }
           
        }

        return array_values($request);
    }

}

$ipv4 = new IPV4();
$ipv4->handle($argv);

Copy the code and replace the placeholder <Your_UNIQUE_API_KEY> with your API key before saving the file. 

This code accepts an IPv4 IP address and validates it using the built-in php function filter_var( ) validation method.

Open a command line terminal window and run the PHP script with a valid IP address.

You can try with other valid IP addresses to obtain country names. You can also try with an invalid address. The script should catch it.

Getting Country from IPv6 IP Address

If your website visitors have an IPv6 address, there is nothing to worry about. The IP geolocation API can extract country names from IPv6 addresses as well.

Here is the modified PHP script for validating and extracting the country from an IPv6 IP address.


<?php

class IPV6
{

    public function handle(array $request)
    {
        $data = $this->parse_argv($request);
        
        try {
            // build required data
            $formData = http_build_query([
                'api_key' => ‘<YOUR_UNIQUE_API_KEY>',
                'ip_address' => $data[0]  
            ]);
            // 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) {
                echo $err;
                exit;
            } else {
                $response = json_decode($response, true);
                echo 'Country: '.$response["country"];
                exit;
            }
        } catch (\Exception $e) {
            echo $e->getMessage();
            exit;
        }
    }


    private function parse_argv(array $argv): array
    {

        $request = [];
        foreach ($argv as $i => $a) {
         
            if (!$i) {
                continue;
            }   

            $isValid = filter_var($a, FILTER_VALIDATE_IP, FILTER_FLAG_IPV6);

            if($isValid) {
                array_push($request,$a);
            } else {
                echo "Invalid IPv6 Format";
                exit;
            }
           
        }

        return array_values($request);
    }
}

$ipv6 = new IPV6();
$ipv6->handle($argv);

Replace the API key, save the file and run it.

The filter_var( ) validation arguments are now updated to check for valid IPv6 format. Therefore, this PHP script, too, will catch any invalid IP address.

Get Country Specific Local Details from IP Address

The API is not limited to the country name. It can extract many localized details about the IP address's geographic location. 

Here is a glimpse of the API JSON response captured from the documentation.

You can see that the API can also find country details, like country code, down to the region and city names for every IP address. 

Let’s figure out how to extract these details from API response in PHP.


<?php

class Country
{

    public function handle(array $request)
    {
        $data = $this->parse_argv($request);
        try {
            // build required data
            $formData = http_build_query([
                'api_key' => '<YOUR_UNIQUE_API_KEY>',
                'ip_address' => $data[0]  
            ]);
            // 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) {
                echo $err;
                exit;
            } else {
                $response = json_decode($response, true);
                echo '
                    IP Address: '.$response['ip_address'].'
                    Country: '. $response['country'].' 
                    State: '.$response['region'].'
                    City: '.$response['city'].'
                ';
            }
        } catch (\Exception $e) {
            echo $e->getMessage();
            exit;
        }
    }


    private function parse_argv(array $argv): array
    {

        $request = [];
        foreach ($argv as $i => $a) {
         
            if (!$i) {
                continue;
            }   

            $isValid = filter_var($a, FILTER_VALIDATE_IP, FILTER_FLAG_NO_PRIV_RANGE);

            if($isValid) {
                array_push($request,$a);
            } else {
                echo "Invalid IP Format";
                exit;
            }
           
        }

        return array_values($request);
    }
}

$ipLoc = new Country();
$ipLoc->handle($argv);

Get Country Specific Global Details from IP Address

If you look closely at the documentation of the IP geolocation API, it also extracts global details about the country, such as continent, time zone, and geolocation coordinates.

Let's see how to extract these parameters from the API response.


<?php

class Geographic
{

    public function handle(array $request)
    {
        $data = $this->parse_argv($request);
        try {
            // build required data
            $formData = http_build_query([
                'api_key' => '<YOUR_UNIQUE_API_KEY>',
                'ip_address' => $data[0]  
            ]);
            // 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) {
                echo $err;
                exit;
            } else {
                $response = json_decode($response, true);
                echo '
                    IP Address: ' . $response['ip_address'] . '
                    Continent: ' . $response['continent'] . '
                    Longitude: '.$response['longitude']. '
                    Latitude: ' . $response['latitude'] . '
                ';
            }
        } catch (\Exception $e) {
            echo $e->getMessage();
            exit;
        }
    }


    private function parse_argv(array $argv): array
    {

        $request = [];
        foreach ($argv as $i => $a) {
         
            if (!$i) {
                continue;
            }   

            $isValid = filter_var($a, FILTER_VALIDATE_IP, FILTER_FLAG_NO_PRIV_RANGE);

            if($isValid) {
                array_push($request,$a);
            } else {
                echo "Invalid IP Format";
                exit;
            }
           
        }

        return array_values($request);
    }
}

$ipGlo = new Geographic();
$ipGlo->handle($argv);

Get Country for Multiple IP Address

This API works for multiple IP addresses. So instead of probing each visitor's IP address with a separate API call, you may want to generate a report of all visitor countries from your web server IP data logs.

You can achieve a report format per your needs by passing multiple IP addresses to the API request. For example, here is how you can do it for a CSV formatted report of IP addresses to country names.


<?php

class MultiIP
{

    public function handle(array $request)
    {
        $data = $this->parse_argv($request);
        
        $info = '';

        foreach ($data as $key => $value) {
            $info .= $this->getDetails($value);
        }

       echo $info;
        
    }


    private function getDetails(string $ip)
    {
        try {
            // build required data
            $formData = http_build_query([
                'api_key' => '<YOUR_UNIQUE_API_KEY>',
                'ip_address' => $ip  
            ]);
            // 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) {
                echo $err;
                exit;
            } else {
                $response = json_decode($response, true);
                return $ip . ',' . $response['country'] . ',' . $response['continent'] . PHP_EOL;
                exit;
            }
        } catch (\Exception $e) {
            echo $e->getMessage();
            exit;
        }

    }


    private function parse_argv(array $argv): array
    {

        $request = [];
        foreach ($argv as $i => $a) {
         
            if (!$i) {
                continue;
            }   

            $isValid = filter_var($a, FILTER_VALIDATE_IP, FILTER_FLAG_NO_PRIV_RANGE);

            if($isValid) {
                array_push($request,$a);
            } else {
                echo "Invalid IP Format";
                exit;
            }
           
        }

        return array_values($request);
    }
}

$ip = new MultiIP();
$ip->handle($argv);

As you can see, the output of this PHP script is a CSV formatted report of visitor IP address mapped to country and continent names.

Based on your requirements, you can modify the report format to deliver an abridged record with country code , region code, and continent code, along with IP data.

Can You Find Country Name from IP Address?

You can find the country name from an IP address, provided the IP address is public and globally addressable. Apart from that, you can also find the city and region names of the IP address within the country. Moreover, with the help of Abstract IP Geolocation API, it is possible to get these details along with timezone, ISP, and location coordinate specific IP address information.

How to find the Country of IP Address?

There is no direct way of decoding the country name from the IP address. But, it is possible to access a database that tracks IP address ranges allocation details across all ISPs operating in various geographies. However, with the help of Abstract IP Geolocation API, it is possible to get this information instantly. IP geolocation API maintains long-standing relationships with ISPs and other data providers to provide highly accurate and consistent country-specific data for IP addresses. Along with the country name, the API also offers valuable information about the location of the IP address, such as region, city, and location coordinates.

Why is IP Address Mapped to Country Name?

IP addresses are allocated to various Internet Service Providers (ISP) in different regions worldwide. All these ISPs operate as autonomous systems, which form the basis for the global routing of Internet traffic to and from all continents. IANA is the body that maintains a set of registries of IP addresses. Both IPv4 and IPv6 addresses are generally assigned hierarchically. ISPs assign users IP addresses. ISPs obtain allocations of IP addresses from a local Internet registry (LIR) or National Internet Registry (NIR), or their appropriate Regional Internet Registry (RIR). Thus all the users are mapped to one of the LIR or NIRs mapped to a country. This arrangement allows for tracking user IP addresses based on country names. If you want complete location details about all the information associated with IP addresses, you can use the Abstract's free Geolocation API.

4.3/5 stars (6 votes)

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 API
API
key now
Abstract's IP Geolocation API comes with libraries, code snippets, guides, and more.
get started for free

Related Articles

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