您想要為使用者貼文實作訪客計數系統,以在主頁上顯示瀏覽次數最多的貼文。雖然您已經有了一個系統,但它會將每次頁面刷新記錄為視圖。您無法使用 Google Analytics(分析),因此您需要一個解決方案來確保只計算唯一身份訪客。
要實現您的目標,您可以實施以下步驟:
<?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(); ?>
透過實作此方法,您可以計算唯一訪客並準確追蹤貼文的受歡迎程度。請記住將 $post_id 變數替換為您要追蹤觀看次數的貼文的實際 ID。
以上是如何在不使用 Google Analytics 的情況下統計我網站的唯一訪客數量?的詳細內容。更多資訊請關注PHP中文網其他相關文章!