phphitcounter

Do not increment on page reload


I've placed a hit counter on my page. It reads a text file, increments the number in the file, and later in the page, I output the incremented value.

$hitsFile   = "hits/exps/stats.txt";
$hits       = file($hitsFile);
$hits[0]++;
$fp = fopen($hitsFile , "w");
flock($fh, LOCK_EX);
fwrite($fp , $hits[0]);
fclose($fp);

My problem is that if I reload the page, the code will increment the hits. I don't want that. I thought of using session to fix that, but with session, in order the increment the hits again, I need to exit the site and visit again. I don't want that either.

I want it to increment not when I reload the page but when I revisit the page.

For example, let's say I have two-page website, Home and Contact, and on contact page I have a hit counter. I don't want the hit counter to increment if I reload(refresh) the contact page, but if I leave the contact page and visit homepage, and later revisit the contact page, I want it to increment.

In short, I don't want it to increment on page reload. Is there a way to do that?


Solution

  • In each of your pages, you need to write the page name in the session.
    Do something like this:

    $_SESSION['page'] = 'contact';
    

    On the pages where you need to count hits, you need to check this session key.
    For example, if you were on page 'contact', then $_SESSION['page'] == 'contact'.
    Now when you go to visit the 'homepage':

    $page = $_SESSION['page'];
    if($page != 'homepage')
    {
        //increment your hits counter
        $_SESSION['page'] = 'homepage';
    }