You want to implement a visitor counting system for user posts to showcase the most viewed posts on the homepage. While you already have a system in place, it records every page refresh as a view. You can't use Google Analytics, so you need a solution that will ensure only unique visitors are counted.
To achieve your goal, you can implement the following steps:
<?php // Establish a connection to your MySQL database $conn = new mysqli("localhost", "username", "password", "database_name"); // Get the current timestamp $timestamp = time(); // Check if the visitor has a unique identifier in a cookie $cookie_name = "visitor_id"; if (isset($_COOKIE[$cookie_name])) { // Visitor has a unique identifier $visitor_id = $_COOKIE[$cookie_name]; } else { // Visitor does not have a unique identifier, create one and store it in a cookie $visitor_id = uniqid(); setcookie($cookie_name, $visitor_id, time() + (60 * 60 * 24 * 30)); // Expires in 30 days } // Check if the visitor already exists in your database $sql = "SELECT id FROM visitors WHERE visitor_id = ?"; $stmt = $conn->prepare($sql); $stmt->bind_param("s", $visitor_id); $stmt->execute(); $result = $stmt->get_result(); // If the visitor already exists, do not count them again if ($result->num_rows > 0) { // Visitor is already in the database, ignore them } else { // Visitor is new, insert them into the database and increment the view count $sql = "INSERT INTO visitors (visitor_id, first_visit) VALUES (?, ?)"; $stmt = $conn->prepare($sql); $stmt->bind_param("ss", $visitor_id, $timestamp); $stmt->execute(); // Increment the view count for the specific post $post_id = 1; // Replace this with the actual post ID $sql = "UPDATE posts SET views = views + 1 WHERE id = ?"; $stmt = $conn->prepare($sql); $stmt->bind_param("i", $post_id); $stmt->execute(); } // Close the database connection $conn->close(); ?>
By implementing this method, you can count unique visitors and accurately track the popularity of your posts. Remember to replace the $post_id variable with the actual ID of the post you want to track views for.
The above is the detailed content of How can I count unique visitors to my site without using Google Analytics?. For more information, please follow other related articles on the PHP Chinese website!