01 <?php
02
03 // function to write the visitor data to the log file
04 function counter_write($filename, $filecontent, $mode='w')
05 {
06 if($fp = fopen($filename,$mode))
07 {
08 fwrite($fp, stripslashes($filecontent));
09 fclose($fp);
10 return true;
11 }else{
12 return false;
13 }
14 }
15
16 // function to handle the counting and tracking logic
17 function counter_count($filename, $ip, $timeframe=1800)
18 {
19 // if the file does not exists, we attempt to create it
20 if(!file_exists($filename))
21 {
22 counter_write($filename, '');
23 }
24 $counterstr = time().'|'.$ip.'|'."\n";
25 $counter = array($ip=>1);
26 $hits = 1;
27 $counterdata = file($filename);
28 $number = count($counterdata);
29 for($i = 0; $i < $number; $i++)
30 {
31 $userdata = explode('|',$counterdata[$i]);
32 if($userdata[0] > time()-$timeframe)
33 {
34 if(array_key_exists($userdata[1],$counter))
35 $counter[$userdata[1]]++;
36 else
37 $counter[$userdata[1]] = 1;
38 $hits++;
39 $counterstr .= $counterdata[$i];
40 }
41 }
42 counter_write($filename, $counterstr);
43 $users = count($counter);
44
45 // change this output to suit your taste
46 $output = '
47 <p>
48 '.$hits.' hit'.($hits > 1 ? 's' : '').'
49 by '.$users.' user'.($users > 1 ? 's' : '').'
50 in the last '.($timeframe/60).' minutes.
51 </p>';
52
53 return $output;
54 }
55
56 // logs the current hit and displays the stats
57 // make sure you point this to a writeable file
58 echo counter_count('tmp/site-hit-counter.txt', $_SERVER['REMOTE_ADDR']);
59
60 ?>