DetThe other two powerful scripting Languages are PHP and JavaScript, which offer a great variety in accomplishing the task as we did earlier.
In this tutorial, we are going to write logic to Detect and Track User IP, Device, and Location in PHP and JavaScript.
Some to be discussed are obtaining the IP of the user using PHP, Detecting Browser, Operating System.
Alongwith device type using PHP, getting Geo-location using JavaScript, and storing all in PHP.
Once our logic is complete, we should have a fully functioning project that will aid us in logging the IP Address.
Alongwith Browser, Operating System, Device Type, Country, City, Longitude, and Latitude.
The file structure should be so simple that we will create a folder and name it user-tracking, and within the same folder.

Above all, We will create two files: index.html, which will be used as the frontend, and track.php as the backend logger. Access More Blogs
Developing Frontend to Detect and Track User IP, Device, and Location
We have to create an index.html file in which we have to write the logic of JavaScript and show the content when fetched there only.
The code, which will help us to detect and Track User IP, Device, and Location, is mentioned below –
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Track User Info</title>
</head>
<body>
<h2>Tracking User Info...</h2>
<script>
// Get user's geolocation using JS
navigator.geolocation.getCurrentPosition(function(position) {
const lat = position.coords.latitude;
const lon = position.coords.longitude;
// Send coordinates to PHP
fetch('track.php', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({
latitude: lat,
longitude: lon
})
})
.then(res => res.text())
.then(data => console.log(data));
}, function(error) {
console.error('Geolocation Error:', error.message);
});
</script>
</body>
</html>Here in this code, we have initialized two variables which is accessing latitude and longitude.
Then we are using the API in the header, which gets the data and converts it to the JSON format.

Developing a Backend to Detect and Track User IP, Device, and Location
Now we have to create a file which will be named as track.php in which we will be giving values to get the data fetched so far.
The code for the same is as follows –
<?php
// Get IP Address
function getUserIP() {
if (!empty($_SERVER['HTTP_CLIENT_IP'])) return $_SERVER['HTTP_CLIENT_IP'];
elseif (!empty($_SERVER['HTTP_X_FORWARDED_FOR'])) return $_SERVER['HTTP_X_FORWARDED_FOR'];
return $_SERVER['REMOTE_ADDR'];
}
// Get Browser Info
function getBrowser() {
$ua = $_SERVER['HTTP_USER_AGENT'];
if (strpos($ua, 'Firefox') !== false) return 'Firefox';
elseif (strpos($ua, 'Chrome') !== false) return 'Chrome';
elseif (strpos($ua, 'Safari') !== false) return 'Safari';
elseif (strpos($ua, 'Edge') !== false) return 'Edge';
elseif (strpos($ua, 'MSIE') !== false || strpos($ua, 'Trident/') !== false) return 'Internet Explorer';
return 'Unknown';
}
// Get Operating System
function getOS() {
$ua = $_SERVER['HTTP_USER_AGENT'];
if (preg_match('/linux/i', $ua)) return 'Linux';
elseif (preg_match('/macintosh|mac os x/i', $ua)) return 'Mac';
elseif (preg_match('/windows|win32/i', $ua)) return 'Windows';
return 'Unknown';
}
// Detect Device Type
function getDevice() {
$ua = $_SERVER['HTTP_USER_AGENT'];
if (preg_match('/mobile/i', $ua)) return 'Mobile';
elseif (preg_match('/tablet|ipad/i', $ua)) return 'Tablet';
return 'Desktop';
}
// Decode JSON sent from JS
$data = json_decode(file_get_contents("php://input"), true);
// Extract JS-provided data
$latitude = $data['latitude'] ?? 'Not Available';
$longitude = $data['longitude'] ?? 'Not Available';
// Use a free API to get location info based on IP
$ip = getUserIP();
$geo = json_decode(file_get_contents("http://ip-api.com/json/{$ip}"), true);
$city = $geo['city'] ?? 'Unknown';
$country = $geo['country'] ?? 'Unknown';
// Collect all user data
$userData = [
'IP Address' => $ip,
'Browser' => getBrowser(),
'OS' => getOS(),
'Device' => getDevice(),
'City' => $city,
'Country' => $country,
'Latitude' => $latitude,
'Longitude' => $longitude,
'Timestamp' => date('Y-m-d H:i:s')
];
// Store in log file
file_put_contents('logs.txt', json_encode($userData) . PHP_EOL, FILE_APPEND);
// Respond with status
echo "User info logged successfully.";
?>In this code, there are several predefined functions, such as getUserIP().
Which is used to detect the Client IP from different headers to bypass the proxies.
Some functions, such as getBrowser(), getOS(), and getDevice(), are kind of semantic functions whose working functionality can be known by the name itself.
json_decode(file_get_contents(“php://input”)): used to read the POST request sent via JavaScript.
http://ip-api.com/json/{ip}: It is a free geo-IP lookup API that is used to fetch the country and city.
File_put_Contents() is used to store logs to logs.txt for record.
Getting the Output
When we run the code the data will be stored in the logs.txt as mentioned below –
{
"IP Address": "______ ",
"Browser": "____",
"OS": "______",
"Device": "_________",
"City": "____________",
"Country": "_______",
"Latitude":_________,
"Longitude": ________,
"Timestamp": "_________"
}There are some limitations in the project that the user must know about –

- This will work on the Localhost only.
- For full Geolocation Access, the user must allow the browser’s GPS Access.
- We can enhance the project by storing the data in MySQL rather than storing it in the logs.txt file.
Conclusion
The project can be of great help when we possess a laptop whose whereabouts or anything regarding it is unfamiliar.
Such as when gaining possession of a used laptop.
Security should be one of the main worries of an individual, as through it, one can be assured that regardless of what the thing may be.
It must be paramount that it is really reliable.
Read our blogs about accomplishing insane jobs with PHP and JavaScript without accessing any external or third-party plug-in.
You can now have your own tailored site at only Rs. 7,499, which includes 1 year of hosting and a domain guarantee. Contact us Now.




