How can PHP be used to count page hits for individual IDs while excluding hits from the same user within a certain time frame?

To count page hits for individual IDs while excluding hits from the same user within a certain time frame, we can use a combination of cookies and database storage. When a user visits a page, we can check if a cookie with a unique identifier for the user exists. If it does not, we can increment the hit count for the specific ID in the database and set a cookie with the user's unique identifier. If the cookie already exists, we can check the timestamp of the last visit and only increment the hit count if the specified time frame has passed.

<?php
// Connect to your database
$pdo = new PDO('mysql:host=localhost;dbname=your_database', 'username', 'password');

// Get the ID of the page
$page_id = $_GET['id'];

// Check if a cookie with a unique identifier exists
if (!isset($_COOKIE['user_id'])) {
    // Increment hit count for the specific ID in the database
    $stmt = $pdo->prepare("UPDATE page_hits SET hits = hits + 1 WHERE page_id = :page_id");
    $stmt->bindParam(':page_id', $page_id);
    $stmt->execute();
    
    // Set a cookie with a unique identifier for the user
    setcookie('user_id', uniqid(), time() + (86400 * 30)); // Cookie expires in 30 days
} else {
    // Check if the specified time frame has passed (e.g., 1 hour)
    $last_visit = $pdo->query("SELECT last_visit FROM user_visits WHERE user_id = '{$_COOKIE['user_id']}'")->fetchColumn();
    
    if (time() - strtotime($last_visit) >= 3600) {
        // Increment hit count for the specific ID in the database
        $stmt = $pdo->prepare("UPDATE page_hits SET hits = hits + 1 WHERE page_id = :page_id");
        $stmt->bindParam(':page_id', $page_id);
        $stmt->execute();
        
        // Update the timestamp of the last visit
        $stmt = $pdo->prepare("UPDATE user_visits SET last_visit = NOW() WHERE user_id = :user_id");
        $stmt->bindParam(':user_id', $_COOKIE['user_id']);
        $stmt->execute();
    }
}
?>