How can the code be modified to ensure that the counter only increments on the home page and displays the current count on other pages?

To ensure that the counter only increments on the home page and displays the current count on other pages, you can use session variables to keep track of the count across different pages. In the code snippet below, we check if the current page is the home page before incrementing the counter. We then store and retrieve the count using session variables to maintain its value across page loads.

<?php
session_start();

if($_SERVER['REQUEST_URI'] == '/'){
    if(isset($_SESSION['counter'])){
        $_SESSION['counter']++;
    } else {
        $_SESSION['counter'] = 1;
    }
}

echo "Counter: " . $_SESSION['counter'];
?>