繁体   English   中英

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

[英]PHP - Edit a specific line in a txt file

我正在为我的网站编程一个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 ,然后在文件末尾打印出来...

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

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

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);

    }
}

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

并将其以json_encode格式存储。

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

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM