diff --git a/db/migrations/001_create_visitor_logs.sql b/db/migrations/001_create_visitor_logs.sql new file mode 100644 index 0000000..0d4aad5 --- /dev/null +++ b/db/migrations/001_create_visitor_logs.sql @@ -0,0 +1,10 @@ +CREATE TABLE IF NOT EXISTS visitor_logs ( + id INT AUTO_INCREMENT PRIMARY KEY, + ip_address VARCHAR(45) NOT NULL, + country VARCHAR(100) DEFAULT 'Unknown', + country_code CHAR(2) DEFAULT '??', + last_activity TIMESTAMP DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP, + session_id VARCHAR(255) NOT NULL, + INDEX (last_activity), + INDEX (ip_address) +); diff --git a/includes/tracker.php b/includes/tracker.php new file mode 100644 index 0000000..2b01d00 --- /dev/null +++ b/includes/tracker.php @@ -0,0 +1,49 @@ +prepare("SELECT id FROM visitor_logs WHERE session_id = ? LIMIT 1"); + $stmt->execute([$session_id]); + $visitor = $stmt->fetch(); + + if ($visitor) { + // Update activity + $stmt = $db->prepare("UPDATE visitor_logs SET last_activity = CURRENT_TIMESTAMP WHERE id = ?"); + $stmt->execute([$visitor['id']]); + } else { + // New session, get GeoIP + $country = 'Unknown'; + $country_code = '??'; + $lat = 0; + $lon = 0; + + // Simple GeoIP via API (Note: This might slow down the first request, but we only do it once per session) + try { + $ctx = stream_context_create(['http' => ['timeout' => 2]]); + $geo = file_get_contents("http://ip-api.com/json/$ip", false, $ctx); + if ($geo) { + $data = json_decode($geo, true); + if ($data && $data['status'] === 'success') { + $country = $data['country']; + $country_code = $data['countryCode']; + $lat = $data['lat'] ?? 0; + $lon = $data['lon'] ?? 0; + } + } + } catch (Exception $e) { + // Silently fail if API is down + } + + $stmt = $db->prepare("INSERT INTO visitor_logs (ip_address, country, country_code, lat, lon, session_id) VALUES (?, ?, ?, ?, ?, ?)"); + $stmt->execute([$ip, $country, $country_code, $lat, $lon, $session_id]); + } +} diff --git a/index.php b/index.php index c60b568..f7a9513 100644 --- a/index.php +++ b/index.php @@ -1,6 +1,9 @@