这是我用来在我的网站上计数的代码。问题是有时它不会计算所有点击次数。
<?php
//acquire file handle
$fd=fopen('counter.txt','c+b');
if (!$fd) die("");
//lock the file - we must do this BEFORE reading, as not to read an outdated value
if (!flock($fd,LOCK_EX)) die("");
//read and sanitize the counter value
$counter=fgets($fd,10);
if ($counter===false) die("");
if (!is_numeric($counter)) {
flock($fd,LOCK_UN);
die("");
}
//increase counter and reconvert to string
$counter++;
$counter="$counter";
//Write to file
if (!rewind($fd)) {
flock($fd,LOCK_UN);
die("");
}
$num=fwrite($fd,$counter);
if ($num!=strlen($counter)) {
flock($fd,LOCK_UN);
die("");
}
//Unlock the file and close file handle
flock($fd,LOCK_UN);
fclose($fd);
?>
我不知道现在该怎么办。有没有更好的方法来编写我的代码或者我应该使用另一种技术?