How Do I Count Unique Visitors to My Site?
Goal: Count unique visitors to your site, considering only one visit per user per day (or week).
Solution (PHP Code):
<?php // Open database connection $conn = new mysqli('localhost', 'root', 'password', 'database'); // Get user's IP address $ip = $_SERVER['REMOTE_ADDR']; // Check if user already visited today (or in the last week) $sql = "SELECT * FROM visitors WHERE ip='$ip' AND last_visit >= DATE_SUB(NOW(), INTERVAL 1 DAY)"; $result = $conn->query($sql); // If user is a new visitor if ($result->num_rows == 0) { // Insert user's IP and current timestamp $sql = "INSERT INTO visitors (ip, last_visit) VALUES ('$ip', NOW())"; $conn->query($sql); // Increment total visitor count $sql = "UPDATE stats SET visits = visits + 1"; $conn->query($sql); } // Get total number of unique visitors $sql = "SELECT COUNT(*) AS total_visitors FROM visitors"; $result = $conn->query($sql); $total_visitors = $result->fetch_assoc()['total_visitors']; // Display the number of unique visitors echo "Total unique visitors: $total_visitors"; // Close database connection $conn->close(); ?>
Explanation:
Alternative Resources:
The above is the detailed content of How Can I Track Unique Visitors to My Website with PHP and MySQL?. For more information, please follow other related articles on the PHP Chinese website!