这是我用于计数的代码。问题在于,有时它不计算所有点击。
<?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');
关于php - 计数器代码计数不正确,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11687467/