PHP计数器与羊群


PHP counter with flock

我有一个计数器的问题。我需要计数两个变量,用|分隔,但有时计数器不会增加变量的值。

number .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比其他计数器计数更多的印象。为什么?我该如何解决这个问题?

我们在高流量网站上使用以下方法来计算印象:

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

在解锁之前尝试执行刷新。你在数据可能被写入之前就解锁了,允许另一次执行。

http://php.net/manual/en/function.fflush.php