session_start();
//grab the IP address
$ip = $_SERVER['REMOTE_ADDR'];
//check whether there is already a session element for IP
if (isset($_SESSION['IP'])){
if ($_SESSION['IP'] == $ip) {
//do nothing as the ip is already stored
$hits = getHits();
} else {
//store the IP in the session data
$_SESSION['IP'] = $ip;
$hits = addHit();
}
}
//display $hits if you want
function addhit(){
$hc = 'hitcounter.txt'; //filename to store the counter number
$lf = 'hc.lock'; //a variable for the lock file
//get the current hit counter value
$cnt = getHits();
$newcnt = $cnt + 1;
$sleepcounter = 0;// protection from stuck lock files
//add a write lock
while (is_file($lf)) {
usleep (10);
if ($sleepcounter >= 100) {
unlink($lf);
}
$sleepcounter++;
}
$fl = fopen($lf, "wb");
fwrite($fl, '££');
fclose ($fl);
//open the file for WRITING
$fh = fopen($hc, "wb");
// write the new figure
fwrite ($fh, $newcnt);
//close the file
fclose($fh);
unlink ($lf); //delete the write lock file
//return the new hitcount
return $newcnt;
}
}
function getHits(){
$hc = 'hitcounter.txt'; //filename to store the counter number
//grab the contents of the file and cast to an integer
$cnt = (int) file_get_contents($hc);
return $cnt;
}