I would recommend using server-side scripting (PHP) for this. Below is a counter script that uses AJAX to increment the counter in "real-time". (Using PHP).
counter.php (configure the parts in red to point to the text files that will be used for the counter - make sure these files have writable permissions [777]):
Code:
<?php
$timeout = 5;
session_start();
header("Cache-Control: no-cache, must-revalidate");
//configuration
$counterTxt = "counter.txt"; //text file for the currently online counter
$hitsTxt = "hits.txt"; //text file for the total hits counter.
//###################### CALCULATE USERS ONLINE #########################
$userip = $_SERVER['REMOTE_ADDR'];
$time = time();
$usersonline = 0;
$alreadyonline = 0;
$onlinetxt = fopen("$counterTxt","r+");
flock($onlinetxt,2);
while (!feof($onlinetxt))
$user[] = chop(fgets($onlinetxt,65536));
fseek($onlinetxt,0,SEEK_SET);
ftruncate($onlinetxt,0);
foreach ($user as $line) {
@list($savedip,$savedtime) = split("\|",$line);
if ($savedip == $userip) {
$savedtime = $time;
$alreadyonline = 1;
}
if ($time < $savedtime + ($timeout)) {
fputs($onlinetxt,"$savedip|$savedtime\n");
$usersonline = $usersonline + 1;
}
}
if (!$alreadyonline) {
fputs($onlinetxt,"$userip|$time\n");
$usersonline = $usersonline + 1;
}
fclose ($onlinetxt);
//###################### CALCULATE HIT COUNTER #########################
$stats = file("$hitsTxt");
$stats = explode("|",$stats[0]);
$unique_today = $stats[0]+0;
$unique_total = $stats[1]+0;
$old_today = $stats[2];
$today = date("Ymd");
if($old_today != $today)
$unique_today = 0;
if(!isset($_SESSION['counted']) || ($_SESSION['counted'] != 1)){
$unique_today++;
$unique_total++;
$_SESSION['counted']=1;
}
$fp = fopen("$hitsTxt","w");
fwrite($fp,$unique_today."|".$unique_total."|".$today);
fclose($fp);
//######################## DISPLAY STATISTICS ##########################
echo 'Currently Online: '.$usersonline.'<BR>
Hits Today: '.$unique_today.'<BR>'
Total Hits: '.$unique_total;
?>
Then place this code wherever you want the counter to appear.
Code:
<div id="counter"></div>
<script type="text/javascript" language="javascript">
if (window.XMLHttpRequest) {
xmlHttp = new XMLHttpRequest();
} else if (window.ActiveXObject) {
xmlHttp = new ActiveXObject("Microsoft.XMLHTTP");
}
function callServer(url) {
xmlHttp.open("GET", url, true);
xmlHttp.onreadystatechange = updatePage;
xmlHttp.send(null);
}
function updatePage() {
if (xmlHttp.readyState == 4) {
var response = xmlHttp.responseText;
document.getElementById("counter").innerHTML = response;
setTimeout("callServer('counter.php')",2500);
}
}
callServer("counter.php");
</script>
Hope this helps, and let me know if you need any more help.
Bookmarks