php - 计数器代码计数不正确

标签 php error-handling

这是我用于计数的代码。问题在于,有时它不计算所有点击。

<?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/

相关文章:

php - PDO 新手,努力将结果的 id 放入变量中

php - 自动完成输入文本类型错误

swift - “ fatal error :在展开可选值时意外发现nil”是什么意思?

windows - 命令文件 : translate Windows error message

c# - 引发异常时不显示自定义错误页面

javascript - 未捕获的无效数据 : data did not match any variant of untagged enum ArgsEnum

php - 我无法将 Bootstrap 4.1.0 链接到我的 Laravel 元素

php - 以多个单元格值(跨行)作为条件的复杂查询?

php - 有没有办法获取变量的名称? PHP-反射

php - 自定义 PDO 错误尝试/捕获