Skip to content
PHP Logo

How can PHP developers ensure that a view counter accurately reflects unique views without being inflated by page refreshes?

To ensure that a view counter accurately reflects unique views without being inflated by page refreshes, PHP developers can utilize cookies or IP address tracking to identify unique visitors. By setting a cookie or storing IP addresses of visitors who have already viewed the page, developers can prevent multiple views from the same user from being counted as unique views.

php
// Check if the user has already viewed the page
if (!isset($_COOKIE['viewed_page'])) {
    // Increment the view counter
    $views = // Get the current view count from database
    $views++;
    
    // Update the view count in the database
    // Set a cookie to prevent multiple views from the same user
    setcookie('viewed_page', true, time() + (86400 * 30)); // Cookie expires in 30 days
}