Brian J Kirk
Brian J Kirk

Reputation: 61

Site Counter for individual database site visits

I currently have a php webcounter on my site, but I would like to have a counter that would be different on every page of my database, so if I were going to visit record 1 it would show a different count then if I were to visit record 56, is there a simple way of doing this with the code I currently have?

session_start();
$counter_name = "counter.txt";

// Check if a text file exists. If not create one and initialize it to zero.
if (!file_exists($counter_name))
{
    $f = fopen($counter_name, "w");
    fwrite($f,"0");
    fclose($f);
}

// Read the current value of our counter file
$f = fopen($counter_name,"r");
$counterVal = fread($f, filesize($counter_name));
fclose($f);

// Has visitor been counted in this session?
// If not, increase counter value by one
if(!isset($_SESSION['hasVisited']))
{
    $_SESSION['hasVisited']="yes";
    $counterVal++;
    $f = fopen($counter_name, "w");
    fwrite($f, $counterVal);
    fclose($f); 
}

Print "views:$counterVal";

I have tried searching this topic but I have been unable to find an answer that helps to solve this problem. My guess is that I would basically have to create a separate text file for each individual site, but I am not sure on the coding that would do that. Thanks in advance for any help you can give.

Upvotes: 0

Views: 117

Answers (1)

Chizzle
Chizzle

Reputation: 1715

You're right, the easiest way to do this is to have a separate text file keeping the count for each page.

$page =  $_SERVER["REQUEST_URI"]; /* Returns The Current url */
$page = str_replace ( '/' ,'-', $page); /*Get rid of the slashes so it can be used as a filename*/
$counter_name = "counter" . $page . ".txt";

Upvotes: 1

Related Questions