我的计数器有问题。我需要计算两个变量,用|
分隔,但有时计数器不会增加变量的值。
numeri.txt(柜台):
6122|742610
这是PHP脚本:
$filename="numeri.txt";
while(!$fp=fopen($filename,'c+'))
{
usleep(100000);
}
while(!flock($fp,LOCK_EX))
{
usleep(100000);
}
$contents=fread($fp,filesize($filename));
ftruncate($fp,0);
rewind($fp);
$contents=explode("|",$contents);
$clicks=$contents[0];
$impressions=$contents[1]+1;
fwrite($fp,$clicks."|".$impressions);
flock($fp,LOCK_UN);
fclose($fp);
我有另一个计数器,它的速度要慢很多,但要精确计算两个值(点击次数和展示次数)。有时,计数器numeri.txt
会比其他计数器计算更多的展示次数。为什么?我该如何解决这个问题?
答案 0 :(得分:0)
尝试在解锁前执行同花。你甚至可以在写入数据之前解锁,允许另一次执行来破坏。
答案 1 :(得分:0)
我们在流量高的网站上使用以下内容来计算展示次数:
<?php
$countfile = "counter.txt"; // SET THIS
$yearmonthday = date("Y.m.d");
$yearmonth = date("Y.m");;
// Read the current counts
$countFileHandler = fopen($countfile, "r+");
if (!$countFileHandler) {
die("Can't open count file");
}
if (flock($countFileHandler, LOCK_EX)) {
while (($line = fgets($countFileHandler)) !== false) {
list($date, $count) = explode(":", trim($line));
$counts[$date] = $count;
}
$counts[$yearmonthday]++;
$counts[$yearmonth]++;
fseek($countFileHandler, 0);
// Write the counts back to the file
krsort($counts);
foreach ($counts as $date => $count) {
fwrite($countFileHandler, "$date:$count\n");
fflush($countFileHandler);
}
flock($countFileHandler, LOCK_UN);
} else {
echo "Couldn't acquire file lock!";
}
fclose($countFileHandler);
}
?>
结果是每日和每月总计:
2015.10.02:40513
2015.10.01:48396
2015.10:88909