PHP中的Yes/No计数器


Yes/No Counter in PHP

我写了这个计数器,它跟踪一个网站的是/否,它工作得很好,问题是文件在写的时候弄乱了。例如,它会从126变成27。该脚本从我编写的iOS应用程序调用,所以很可能有多个连接同时修改文件,我认为这就是导致问题的原因。我不是一个真正的PHP家伙,所以我希望一些见解可以使代码更好一点,并处理多个同时连接。

<?php
        $yes_file = 'yes.txt';
        $no_file  = 'no.txt';
        $yes_count = file_get_contents($yes_file);
        $no_count = file_get_contents($no_file);
        if ($_GET['result'])
        {
                if( strcmp($_GET['result'], "YES") ) {
                        $no_count+=1;
                        file_put_contents($no_file, $no_count);
                }
                else {
                        $yes_count+=1;
                        file_put_contents($yes_file, $yes_count);
                }
        }
        $total = $yes_count + $no_count;
        echo "{'"yescount'":" . $yes_count.",";
        echo "'"nocount'":" . $no_count.",";
        echo "'"total'":" . $total."}";
?>

谢谢!

这样会更有效率。

仅供参考,数据库在增加时对行/表设置写锁,这与我下面所做的相同,因此数据库不是解决方案-解决方案是写锁(通过数据库或通过PHP)。您可以使用flock,但我发现这很乱,所以我只使用临时文件。

我的代码的唯一问题是,如果服务器在这个脚本中间崩溃,那么写锁将留在原地(MySQL有时也有这个问题)。我通常通过在文件中写入time()并检查它不超过一个小时或其他东西来解决这个问题。但对你来说,这可能是不必要的。

<?php
// Your variables
$yes_file = 'yes.txt';
$no_file  = 'no.txt';
if (isset($_GET['result']))
{
// Write lock
while(file_exists('temporaryfile')) usleep(100000);
file_put_contents('temporaryfile','1');
$yes_count = (int)file_get_contents($yes_file);
$no_count = (int)file_get_contents($no_file);
// Increment
if ($_GET['result']=='YES')
    {
    $yes_count++;
    file_put_contents($yes_file, $yes_count);
    }
else
    {
    $no_count++;
    file_put_contents($no_file, $no_count);
    }
// Unlock
unlink('temporaryfile');
}
else // No need for any lock so just get the vars
{
$yes_count = (int)file_get_contents($yes_file);
$no_count = (int)file_get_contents($no_file);
}
$total = $yes_count + $no_count;
echo "{'"yescount'":$yes_count,'n'"nocount'":$no_count,'n'"total'":$total}";

首先,我建议使用数据库系统来跟踪计数器。

关于您的问题,在读-更新-写周期期间羊群()文件将会很有帮助。