我有个柜台的问题。我需要计算两个用|分隔的变量,但有时计数器不会增加变量的值。
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比其他计数器计数更多的印象。为什么?我该如何解决这个问题呢?
发布于 2015-10-10 03:45:45
我们在我们的高流量站点上使用以下内容来统计印象:
<?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发布于 2013-05-15 09:07:15
尝试在解锁之前执行刷新。您甚至在数据可能被写入之前就解锁了,从而允许另一次执行崩溃。
http://php.net/manual/en/function.fflush.php
https://stackoverflow.com/questions/16495366
复制相似问题