26th May 2008 - 3 minutes read time
To create a simple PHP visit counter you will need to create a plain blank text file called counter.txt.
Put the following two functions into a file and include it at the top of any page that you want to have counted.
The loadCounter() function.
function loadCounter()
{
if ( file_exists('counter.txt') ) {
$n = file_get_contents('counter.txt');
return intval($n);
}
return 0;
}
The updateCounter() function.
function updateCounter($i=1)
{
$n = loadCounter();
$n += $i;
$fp = fopen('counter.txt',"w+");
fwrite($fp, $n);
fclose($fp);
return $n;
}
The two functions work together to create the counter. If you only want to display the number of times that a page has been visited then just call the loadCounter() function.