Link to home
Start Free TrialLog in
Avatar of dimmergeek
dimmergeekFlag for United States of America

asked on

Unique page visits

I have a website with several pages.
My client would like to see a hit counter for each page.
I'd like to do this with a session.
I have a table with IP, URL, and timestamp fields.
Here is the code that is included on each PHP page of the site:

<?php
  session_start();
  include '../dbConn.php';
    $host = $_SERVER['HTTP_HOST'];
    $script = $_SERVER['SCRIPT_NAME'];
    $currentURL = $host . $script;
    //echo "Current page is: " . $currentURL;
    
    if(((!isset($_SESSION['lastPage'])) or ($_SESSION['lastPage'] <> $currentURL)) and (!isset($_SESSION['userIP']))) {
        $userIP = $_SERVER['REMOTE_ADDR'];
        $_SESSION['userIP'] = $userIP;
        //echo "You're IP address is: " . $userIP;
        $vDate = date("Y-m-d");
        $vTime = date("H:i:s");
        
        $mSQL = "INSERT INTO `hitcount` (`URL`,`IP`) VALUES ('$currentURL', '$userIP')";
        mysqli_query($con,$mSQL);
    }
    
    $mSQL = "SELECT COUNT(*) AS `visits` FROM `hitcount` WHERE `URL` = '$currentURL'";
    $result=$con->query($mSQL);
    while($row = $result->fetch_array()) {
        $cntValue = str_pad($row['visits'], 10, "0", STR_PAD_LEFT);
    }
    $_SESSION['lastPage'] = $currentURL;
?>

Open in new window


It's kinda working...
When you visit the home page the counter increments and shows the newest value.
However, when you visit subsequent pages, the count DOES NOT increment.
I want to exclude multiple visits to the sme page in the same session so I can track "unique" visits to each page and avoid F5 artificially inflating the results.
ASKER CERTIFIED SOLUTION
Avatar of Gary
Gary
Flag of Ireland image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
The professional solution is Google Analytics.  You can supplement that with your own hit counter, but that's kind of a 1998 idea.  You won't see any professionally built web site with a hit counter today.  The session may not be a useful part of the answer because it is lost after any period of inactivity.  I wouldn't worry about people hitting the F5 key -- that's an edge case.

You might think about adding the count to the data base table.  If you keep one record for each visitor, you'll have a very long table, indeed!

Looks like it does not display $cntValue anywhere.
Avatar of dimmergeek

ASKER

Thanks! So much simpler than what I had.
Ray, thank you for your post.
The client is requesting the counter....I tried to steer him away.
This code is counter.php which is an include on subsequent pages.
$cntValue is used by the parent page.