Php 计数器代码计数不正确

Php 计数器代码计数不正确,php,error-handling,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 s

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

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

有太多的
die(“”)$counter++$counter=“$counter”这更简单,
文件内容('counter.txt')
$var=file\u get\u contents('counter.txt')
@GeoPhoenix
file\u put\u contents()
file\u get\u contents()
不支持锁定,也不会处理冲突。@MathieuImbert,但我没有单击按钮就尝试过。我已经试了很多次了。@user1426486正如@PLB所说,你必须调试你的脚本,我们不能帮你。试着在它死的时候回显它:
die(“1”)
die(“2”)
。。。看看它到底在哪里失败。