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(“”)在您的脚本中,不可能说出哪个退出脚本。在其中添加一些描述。最后,PHP是动态类型化语言,这意味着您不需要强制转换东西。我的意思是$counter++$counter=“$counter”代码>这更简单,文件内容('counter.txt')
,$var=file\u get\u contents('counter.txt')
@GeoPhoenixfile\u put\u contents()
和file\u get\u contents()
不支持锁定,也不会处理冲突。@MathieuImbert,但我没有单击按钮就尝试过。我已经试了很多次了。@user1426486正如@PLB所说,你必须调试你的脚本,我们不能帮你。试着在它死的时候回显它:die(“1”)
,die(“2”)
。。。看看它到底在哪里失败。