View Full Version : PHP: text/graphical hit/visitor counter in PHP


Eric
This is a simple hit/visitor counter I threw together for anyone to use on their web site if they want. Feel free to modify it to suit your needs. You can download the entire script and installation instructions in the attached zip file. You can view a demo of it functioning as a text counter and counting only unique visits here http://www.coolesthost.com/simpcounter/unique/simpcounter.php and a demo of it functioning as graphical hit counter and counting all hits here http://www.coolesthost.com/simpcounter/simpcounter.php.

You can view the code below.


<?php

// CONFIGURATION SECTION - You CAN EDIT THE SETTINGS BELOW //
$countfile = "count.txt"; # The name/location of the count log file. You shouldn't need to change this.
$iplogfile = "iplog.txt"; # The name/location of the ip log file. You shouldn't need to change this.
$imgdir = "http://www.yourdomain.com/simpcounter/"; # The url to the directory contatining your images including the traling slash
$imgext = ".gif"; # The extension of your images, ( jpg, png, etc. )
$usetextcounter = 0; # 1 = use text based hit counter, 0 = use graphical counter
$countonlyunique = 0; # 0 = count all hits/pageloads, 1 = count only unique visits
// END CONFIGURATION SECTION //

$count = file($countfile);

if ($countonlyunique == 1) {
$curtime = getdate();

# Empties the ip log file if page is accessed between 12 and 12:01 AM #
# Hopefully someone will access your page between 12 and 12:01 AM :D #
if ($curtime['hours'] == 00 && $curtime['minutes'] == 00) {
$file = fopen($iplogfile, "w");
fwrite($file, "");
fclose($file);
}

$ip = getenv("REMOTE_ADDR");
$curips = file($iplogfile);

foreach ($curips as $key => $value) {
$curips[$key] = trim($value);
}

$curvisitor = (in_array($ip, $curips)) ? 1 : 0;
$unique = fopen($iplogfile, "a");
fwrite($unique, "$ip\r\n");
fclose($unique);

if ($curvisitor != 1) {
$file = fopen($countfile, "w");
fwrite($file, $count[0]+1);
fclose($file);
}
}
else {
$file = fopen($countfile, "w");
fwrite($file, $count[0]+1);
fclose($file);
}

for($i = 0; $i < strlen($count[0]); $i++) {
$curcount = substr($count[0], $i, 1);

if ($usetextcounter == 1) {
echo "$curcount";
}
else {
echo "<img src=\"$imgdir$curcount$imgext\">\n";
}
}

?>