How can a visitor counter be implemented in PHP to only increment the count when the page is initially opened, not on page reload?

To implement a visitor counter in PHP that only increments the count when the page is initially opened, you can use a session variable to keep track of whether the page has been visited before. If the session variable is not set, increment the counter and set the session variable to indicate that the page has been visited.

<?php
session_start();

if (!isset($_SESSION['visited'])) {
    // Increment visitor count
    $file = 'counter.txt';
    $current_count = file_get_contents($file);
    $current_count++;
    file_put_contents($file, $current_count);
    
    // Set session variable to indicate page has been visited
    $_SESSION['visited'] = true;
}

// Display visitor count
echo "Visitor count: " . file_get_contents('counter.txt');
?>