1

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

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计算的展示次数比其他计数器多。为什么?我怎样才能解决这个问题?

4

2 回答 2

1

我们在高流量网站上使用以下内容来计算展示次数:

<?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
于 2015-10-09T19:45:44.837 回答
0

尝试在解锁前执行冲洗。您甚至可能在写入数据之前解锁,从而允许另一个执行破坏。

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

于 2013-05-15T01:07:14.917 回答