Finding the Geolocation and country information of a user is necessary for most websites. Probably you need to show different content based on a user’s country, show different prices as per the country’s currency codes, etc. In these scenarios, you need to find the Geolocation of a user and serve content accordingly.
In this article, I show you how to find Geolocation using the IP address of a user in PHP. We are going to use the ipapi service which provides both free and premium plans.
Getting Started
First, check out the pricing of ipapi and pick up the suitable one. Once you sign up with them, you will get access to the dashboard. From here, get your access key which will be required to call the ipapi endpoint.
In order to get geolocation from an IP address, you need to call the API endpoint along with the API key. In return, you will get the geolocation information.
I will call the API using PHP cURL, Guzzle, and Vanilla JavaScript. The user can choose any of the options for their application.
Get Geolocation using IP Address
Usually, we need to fetch a user’s IP address dynamically. I am writing a method below which will return the IP address.
<?php
// get user's IP address
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;
}
Using cURL
To use the PHP cURL, you need to make sure it is enabled on your server.
Through cURL, I will give a call to the ipapi endpoint providing the user’s IP address, and print the response.
$ip_address = getUserIpAddr();
$access_key = 'API_ACCESS_KEY';
$url = "http://api.ipapi.com/$ip_address?access_key=$access_key";
$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);
Upon running the above code, you will get the output something like below.
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.ipapi.com/flags/in.svg [country_flag_emoji] => IN [country_flag_emoji_unicode] => U+1F1EE U+1F1F3 [calling_code] => 91 [is_eu] => ) )
Using Guzzle
Guzzle is a PHP HTTP client for sending HTTP requests. It is an alternative to cURL. It provides much clean code and a better experience for developers.
To get started with Guzzle, you need to install it using the Composer command below:
composer require guzzlehttp/guzzle
Next, write the code below which calls the API through the Guzzle library.
<?php
require_once "vendor/autoload.php";
use GuzzleHttp\Client;
$ip_address = getUserIpAddr();
$access_key = 'API_ACCESS_KEY';
try {
$client = new Client([
// Base URI is used with relative requests
"base_uri" => "http://api.ipapi.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
It may be possible you have built your application in JavaScript. Or you want to get geolocation from IP using JavaScript only. In such a case, with the help of Fetch API, you can interact with the ipapi and get the geolocation.
var access_key = 'API_ACCESS_KEY';
var ip_address = 'IP_ADDRESS';
fetch('http://api.ipapi.com/'+ip_address+'?access_key=' + access_key)
.then(response => response.json())
.then(data => {
console.log(data);
});
That’s it! This is how we get Geolocation using the IP address. Please share your thoughts and suggestions in the comments section below.
Related Articles
- Laravel Geoip Library – Find Out Geolocation Using IP Address
- How to Get Geolocation from IP in PHP
- How to Use Guzzle – A PHP HTTP Client for Sending HTTP Requests
If you liked this article, then please subscribe to our YouTube Channel for video tutorials.