To create a minimal JS+PHP webpage analytics system to track the necessary data of the user, we can use the following steps:
Step 1: Create a PHP file to receive the data and save it into a .log file (log.php)
<?php
if (!empty($_POST['data'])) {
$data = $_POST['data'];
$log_file = fopen('analytics.log', 'a');
fwrite($log_file, $data . PHP_EOL);
fclose($log_file);
}
?>
Step 2: Create the JavaScript (analytics.js) to collect and send the data to the PHP file:
function gatherData() {
const data = {
ip: '', // To be filled in by PHP
referrer: document.referrer,
location: {}, // To be filled in by an IP geolocation API
browserInfo: navigator.userAgent,
device: '', // To be filled in by a library to detect device properties
url: window.location.href,
title: document.title,
userBehavior: {}, // To be filled in with event listeners for clicks, scrolls etc.
preferences: navigator.language || navigator.userLanguage,
demographics: {}, // To be filled in, potentially by a user login system
};
return data;
}
function sendData(data) {
fetch('/log.php', {
method: 'POST',
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify({ data: JSON.stringify(data) }),
});
}
async function getUserIP() {
const response = await fetch('https://api.ipify.org?format=json');
const ipData = await response.json();
return ipData.ip;
}
async function getLocationData(ip) {
// Replace {API_KEY} with your actual key.
const response = await fetch(`http://ip-api.com/json/${ip}?fields=status,country,regionName,city,zip,lat,lon`);
const locationData = await response.json();
return locationData;
}
(async () => {
const data = gatherData();
data.ip = await getUserIP();
data.location = await getLocationData(data.ip);
sendData(data);
})();
Step 3: Include the analytics.js script in your HTML pages:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Test Page</title>
<script src="analytics.js" defer></script>
</head>
<body>
<h1>Test Page</h1>
</body>
</html>
That's it! Now when someone accesses the HTML page that has the analytics.js script, it will send the gathered data to log.php, which will save it into a .log file.
Please note that this is a minimal solution for demonstrative purposes. It's meant to provide a starting point for building your own custom analytics system, but it might not cover all your needs. Please be aware that this solution does not handle GDPR compliance or data privacy concerns, and is suggested for educational purposes only.