Get user location in PHP
In this article, we will teach you, how you can get user location in PHP. We have a users table where we are saving the user’s location and the time when the last location was fetched.
CREATE TABLE users (
id BIGINT UNSIGNED AUTO_INCREMENT PRIMARY KEY,
name VARCHAR(255) NOT NULL,
email VARCHAR(255) NOT NULL UNIQUE,
password VARCHAR(255) NOT NULL,
location JSON NULL DEFAULT NULL,
last_location_at TIMESTAMP NULL DEFAULT NULL
);
The most important columns are “location” and “last_location_at”. We will be fetching the user’s location every 24 hours. The following code will fetch the user location in PHP.
if (isset($_SERVER['HTTP_X_FORWARDED_FOR']))
{
$client_ip = $_SERVER['HTTP_X_FORWARDED_FOR'];
}
else if (isset($_SERVER['HTTP_X_REAL_IP']))
{
$client_ip = $_SERVER['HTTP_X_REAL_IP'];
}
else
{
$client_ip = $_SERVER['REMOTE_ADDR'];
}
$user_agent = $_SERVER['HTTP_USER_AGENT'];
$timestamp = strtotime($user->last_location_at);
$current_timestamp = time();
$difference = $current_timestamp - $timestamp;
$twenty_four_hours_in_seconds = 24 * 60 * 60;
if ($difference >= $twenty_four_hours_in_seconds)
{
$curl = curl_init();
curl_setopt_array($curl, [
CURLOPT_URL => "http://www.geoplugin.net/json.gp?ip=" . $client_ip,
CURLOPT_RETURNTRANSFER => true,
CURLOPT_POST => true,
CURLOPT_POSTFIELDS => json_encode([]),
CURLOPT_HTTPHEADER => [
"Content-Type: application/json"
]
]);
$response = curl_exec($curl);
if (curl_errno($curl))
{
$error = curl_error($curl);
}
else
{
$response = json_decode($response);
if ($response->geoplugin_status == 200)
{
$location = [
"city" => $response->geoplugin_city,
"continent" => $response->geoplugin_continentName,
"continentCode" => $response->geoplugin_continentCode,
"country" => $response->geoplugin_countryName,
"countryCode" => $response->geoplugin_countryCode,
"currencyCode" => $response->geoplugin_currencyCode,
"currencySymbol" => $response->geoplugin_currencySymbol,
"currencyConverter" => $response->geoplugin_currencyConverter,
"latitude" => $response->geoplugin_latitude,
"longitude" => $response->geoplugin_longitude,
"region" => $response->geoplugin_region,
"ipAddress" => $response->geoplugin_request,
"timezone" => $response->geoplugin_timezone,
"user_agent" => $user_agent
];
$location = json_encode($location);
// UPDATE `users` SET location = '$location', last_location_at = NOW() WHERE id = 2
}
}
curl_close($curl);
}
Explanation:
- Line 01-12: We are fetching the user’s IP address. When a user accesses the web server through a proxy or load balancer, the “REMOTE_ADDR” does not provide the actual IP address, rather it provides the IP address of the load balancer. That is why we are checking if the “HTTP_X_FORWARDED_FOR” or “HTTP_X_REAL_IP” headers are present. These headers are present when the user accesses the web server via proxy or load balancer.
- Line 14: Getting the user’s device and browser information. It will tell if the user is using Chrome, Firefox, Safari, or whatever the browser. It will also tell the operating system he is using, if it is Mac OS, Windows, or Linux.
- Line 16: Here we are getting the timestamp since the last location was fetched of that user. You might be getting this value from the database. If it is null, then it will return the seconds since 1970, which is good in case of null.
- Line 18: Get the current timestamp in seconds.
- Line 20: Get the difference between 2 times.
- Line 22: Calculate how many seconds are there in 24 hours.
- Line 24: Check if the time has passed 24 hours.
- After that, I am calling a GeoPlugin API and passing the client’s IP address to it. I am saving all the required fields returned from API in a variable $location and converting that to JSON string. Then you can save that $location string in your database. Make sure to update the last_location_at to the current timestamp. This will make sure that the next location will be fetched after 24 hours.
One more thing:
You can show the user location on Google Maps too. You can follow this guide.
This feature has been practically implemented in an open-source Laravel boilerplate.