You need to employ some kind of file locking mechanism. I'm not sure if it would solve your problem, but try it.
http://www.php.net/manual/en/function.flock.php
Change your code to:
function HitCounter ($CounterFile)
{
if(file_exists($CounterFile)) {
if(!($fp = fopen($CounterFile, "r")))
return ("Cannot read $CounterFile? hmmm");
flock($fp, 2);
$count = (int) fread($fp, 30);
flock($fp, 3);
fclose($fp);
$count++;
$count2 = number_format($count);
if (!($fp = fopen($CounterFile, "w"))) return ("Cannot write to $CounterFile. Did you chmod 666 the file?");
flock($fp, 2);
fwrite($fp, $count);
flock($fp, 3);
fclose($fp);
return ($count);
}
}
Its only an advisory lock and I don't know if it would work, but its worth a try. I don't have much knowledge of file locking in PHP.
A database would be better, but if all you want is a counter and nothing else than this would be fine if it works.