How to Get Geolocation from IP in PHP

Are you looking to fetch the user’s Geolocation from an IP address in PHP? Using Geolocation you would know where your website visitors are located. It can be used to know your target audience.

Based on the user’s location you can show the relevant content to them. You might want to see different prices, different plans, or whatever as per your business requirement.

To locate the user’s position, HTML Geolocation API is available. But this API works on a permission basis. It popups a user and asks for their permissions then only it works.

The users can overcome this situation using the service called ipstack. In this article, we study how to get Geolocation from IP in PHP using a ipstack service.

Get ipstack API Key

For getting started, you need to first sign up on ipstack. The ipstack provides different levels of services ranging from free to enterprise level. If you are using this service for the first time, I recommend going for free plans. At the time of writing this article, free service allows 5000 requests per month. That means you can check the Geolocation of 5000 IPs for free every month.

Once you register with ipstack, you will get your Access Key. This key is required when we call the ipstack API endpoint.

Below is the screenshot of your ipstack dashboard where you can copy the Access Key.

access-key

Get Geolocation from IP in PHP

You are ready with your ipstack access key. Now we can start using their service and get Geolocation from an IP address.

As we need to give an API call, we will use cURL, Guzzle, and Vanilla JavaScript one by one. Let’s start with PHP cURL.

<?php
// set API Access Key
$access_key = 'IPSTACK_ACCESS_KEY';
 
// set ip address
$ip_address = 'IP_ADDRESS';

try {
    // Initialize CURL:
    $ch = curl_init('http://api.ipstack.com/'. $ip_address .'?access_key='. $access_key);  
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    
    // Store the data:
    $json = curl_exec($ch);
    curl_close($ch);

    $arr_result = json_decode($json, true);
    print_r($arr_result);
} catch(Exception $e) {
    echo $e->getMessage();
}

Replace the placeholders with their values and run the code. In return, you will get a response like:

Array
(
    [ip] => 103.47.153.189
    [type] => ipv4
    [continent_code] => AS
    [continent_name] => Asia
    [country_code] => IN
    [country_name] => India
    [region_code] => MH
    [region_name] => Maharashtra
    [city] => Pune
    [zip] => 411048
    [latitude] => 18.469999313354
    [longitude] => 73.890998840332
    [location] => Array
        (
            [geoname_id] => 1259229
            [capital] => New Delhi
            [languages] => Array
                (
                    [0] => Array
                        (
                            [code] => hi
                            [name] => Hindi
                            [native] => हिन्दी
                        )

                    [1] => Array
                        (
                            [code] => en
                            [name] => English
                            [native] => English
                        )

                )

            [country_flag] => http://assets.ipstack.com/flags/in.svg
            [country_flag_emoji] => IN
            [country_flag_emoji_unicode] => U+1F1EE U+1F1F3
            [calling_code] => 91
            [is_eu] => 
        )

)

You can see how much information we can get by just sending an IP address. We are almost getting all the information one can need from IP. A user can also send multiple IPs as comma-separated.

Using Guzzle

You may want to use Guzzle instead of cURL. In order to work with cURL, its extension needs to be enabled on the server which is not the case for Guzzle. Plus, Guzzle provides a much cleaner code than cURL.

Install the Guzzle library using the command:

composer require guzzlehttp/guzzle

Next, write the code below which will get Geolocation using the Guzzle.

<?php
require_once "vendor/autoload.php";
 
use GuzzleHttp\Client;
 
// set API Access Key
$access_key = 'IPSTACK_ACCESS_KEY';
 
// set ip address
$ip_address = 'IP_ADDRESS';

try {
    $client = new Client([
        // Base URI is used with relative requests
        "base_uri" => "http://api.ipstack.com",
    ]);
    
    $response = $client->request("GET", "/$ip_address", [
        "query" => [
            "access_key" => $access_key,
        ]
    ]);
    
    //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

If you are building a project using the JavaScript framework then you can use the Fetch API to call the ipstack endpoint and receive a response.

var access_key = 'IPSTACK_ACCESS_KEY';
var ip_address = 'IP_ADDRESS';

fetch('http://api.ipstack.com/'+ip_address+'?access_key=' + access_key)
.then(response => response.json())
.then(data => {
    console.log(data);
});

I hope you may learn about how to get Geolocation from IP using ipstack. I would like to hear your thoughts and suggestions in the comment section below.

Related Articles

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 *