【问题标题】:PHP - Edit a specific line in a txt filePHP - 编辑 txt 文件中的特定行
【发布时间】:2014-02-20 08:46:41
【问题描述】:

我正在为我的网站编写访问计数器...

文本文件应如下所示:

  • 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,并将其打印在文件末尾...

如何将新值写入正确的行?

【问题讨论】:

标签: php cookies counter


【解决方案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 并将其存储在文本文件中。

【讨论】:

    猜你喜欢
    • 2022-01-13
    • 1970-01-01
    • 2013-03-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多