计数器代码计数不正确



这是我在网站上计数时使用的代码。问题是,有时它并没有计算所有的点击量。

<?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);
?>

我不知道现在该怎么办。有没有更好的方法来编写代码,或者我应该使用其他技术?

根据与OP的聊天讨论,在尝试了不同的方法后,我们得出的结论是,使用数据库来实现点击计数器并处理对数据的并发访问会更方便。

mysql_connect(HOSTNAME, USERNAME, PASSWORD); 
mysql_select_db(DATABASE); 
mysql_query('UPDATE tbl_click SET click = click + 1'); 

最新更新