To determine the user's location, we need their IP address and a database with a list of IP addresses and their associated geographic data. However, since we've already implemented a solution using a database in this article, today we’ll make the task slightly more complex and interact with an external service via its API to retrieve all the information we need — time zone, latitude, longitude, country, and city.
About the service
We’ll use ip-api.com as our geo data service. By visiting the documentation page and reviewing it, we can understand that to get the required information, we should perform the following request:
http://ip-api.com/json/{query}?lang=ruWhere:
{query} — the IP address we want to query
lang — language (we’ll use “ru” for this example)
Additionally, we can pass extra parameters (fields) in the “fields” parameter to limit the response to only the specified fields.
Let’s get started
Now that we’ve chosen a service to determine the user's location by IP, we need to obtain the user’s IP address. How to do this is described in the article “How to determine a user's IP in PHP”. Next, we’ll make a CURL request in PHP to the ip-api site and retrieve the desired data in response. That’s it.
Here’s the implementation:
$ch = curl_init();
curl_setopt_array($ch, [
CURLOPT_URL => 'http://ip-api.com/json/'.user_ip().'?lang=ru',
CURLOPT_RETURNTRANSFER => true,
]);
$exec = curl_exec($ch);
$getinfo_ar = curl_getinfo($ch);
if(empty($getinfo_ar['http_code']) || $getinfo_ar['http_code'] != 200)
{
die('Unable to determine user geo-data');
}
$json_ar = json_decode($exec, true);
echo "<pre dir='ltr'>$json_ar = ";print_r($json_ar); echo "</pre>";
curl_close($ch);Let’s explain a few details:
$ch = curl_init(); curl_setopt_array($ch, [ CURLOPT_URL => 'http://ip-api.com/json/'.user_ip().'?lang=ru', CURLOPT_RETURNTRANSFER => true, ]); $exec = curl_exec($ch); $getinfo_ar = curl_getinfo($ch); /* … */ curl_close($ch);
A basic CURL call with two parameters.
In the “CURLOPT_URL” constant, we specify the URL to which we’ll make the request. In our URL, the function user_ip() returns the IP address of the visitor (note: doesn’t work on localhost).
The “CURLOPT_RETURNTRANSFER” parameter tells CURL that we want to get the result via the “curl_exec()” function.
The “curl_getinfo($ch)” function returns headers for the request. This is used to check the response code. If it’s not 200, we show an error:
if(empty($getinfo_ar['http_code']) || $getinfo_ar['http_code'] != 200)
{
die('Unable to determine user geo-data');
}Otherwise, we assume the data is valid, decode it using “json_decode”, and display the resulting array:
$json_ar = json_decode($exec, true); echo "<pre dir='ltr'>$json_ar = ";print_r($json_ar); echo "</pre>";
As you can see, it’s quite simple. It took me around five minutes to write the code. Maybe even three.
All the best!
