How can PHP cookies be effectively used in conjunction with a counter script to track unique visits without affecting its display?

When using PHP cookies in conjunction with a counter script to track unique visits, it is important to set a cookie to mark each unique visitor. This cookie can then be used to check if a visitor has already been counted before incrementing the counter. By doing this, the counter will accurately track unique visits without affecting its display.

// Check if the cookie is set
if(!isset($_COOKIE['visited'])){
    // Set a cookie to mark the visitor
    setcookie('visited', 'true', time() + 3600 * 24); // Cookie expires in 24 hours
    
    // Increment the counter
    $countFile = 'counter.txt';
    $count = (file_exists($countFile)) ? file_get_contents($countFile) : 0;
    file_put_contents($countFile, ++$count);
}

// Display the counter
echo 'Unique visits: ' . $count;