PHP - 编辑txt文件中的特定行

时间:2014-02-20 08:46:41

标签: php cookies counter

我正在为我的网站编程一个visitcounter ...

文本文件应如下所示:

  • index.php:4次观看
  • contact.php:6
  • 观点等。

这是我的代码:

function set_cookie(){ 
    setcookie("counter", "Don't delete this cookie!", time()+600); 
}

    function count_views(){
        $page         = basename($_SERVER['PHP_SELF']);
        $file         = fopen("counter.txt","r+");
        $page_found   = false;

        if (!isset($_COOKIE['counter'])) {
            while (!feof($file)) {
                $currentline = fgets($file);
                if(strpos($currentline, ":")){
                    $filecounter = explode(":", $currentline);
                    $pif = $filecounter[0]; $counterstand = $filecounter[1];
                    if ($pif == $page) {
                        $counterstand = intval($counterstand);
                        $counterstand++;
                        fseek($file, -1);
                        fwrite($file, $counterstand);
                        $page_found = true;
                        set_cookie();
                    }
                }
            }
            if (!$page_found) { fwrite($file, $page . ": 1\n"); }
            fclose($file);
        }
    }

现在我的问题: 每次我访问该页面时,他都无法更新新值。所以最后它看起来像这样

  • home.php:1
  • index.php:1
  • 2222

看起来他从文件名后面的正确行中取1,并将其打印在文件末尾...

如何在正确的行中写入新值?

1 个答案:

答案 0 :(得分:0)

这是另一种将数据存储在经常更改的文本文件中的方法。

function count_views(){
    $page = basename($_SERVER['PHP_SELF']);
    $filename = "counter.txt";


    if (!isset($_COOKIE['counter'])) 
    {
        $fh = fopen($filename, 'r+');
        $content = @fread($fh,filesize($filename));
        $arr_content = json_decode($content, true);

        if(isset($arr_content[$page]))
        {
            $arr_content[$page] = $arr_content[$page]+1;
        }
        else
        {
            $arr_content[$page] = 1;
        }

        $content = json_encode($arr_content);
        @ftruncate($fh, filesize($filename));
        @rewind($fh);
        fwrite($fh, $content);

    }
}

这里我们使用一个数组,其中key是页面,值是计数器。

我们将它以json_encode格式存储在其中。

每当我们想要更新特定页面计数时。读取文件中写入的json在php数组中解码并在页面存在时更新计数,如果数组中不存在页面索引,则为新页面分配1。

然后我们再次在json中对其进行编码并将其存储在文本文件中。

相关问题