2014-02-20 137 views
0

我编程,我的网站一visitcounter ...PHP - 编辑特定行的txt文件

文本文件应该是这样的:

  • 的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

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

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

+0

尝试[this](http://stackoverflow.com/questions/7859840/php-fetching-a-txt-file-and-editing-a-single-line?rq=1) –

+1

您可以存储在您的texfile一个包含你的数据的json数组。每次将值存储在数组中并将其编码到json中并存储到文本文件中。当你想检索它。读数组中的文件解码json并使用它。 –

+1

http://stackoverflow.com/questions/3004041/how-to-replace-a-particular-line-in-a-text-file-using-php http://stackoverflow.com/questions/12489033/php -modify-a-line-in-a-text-file http://stackoverflow.com/questions/18991843/replace-line-in-text-file-using-php http://www.dreamincode .net/forums/topic/207017-how-to-change-a-certain-line-of-a-text-file/ http://forums.devshed.com/php-development-5/how-to- change-specific-line-in-text-file-85294.html http://www.linuxquestions.org/questions/programming-9/php-read-file-line-by-line-and-change-a-特定行-523519 / –

回答

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

    } 
} 

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

我们把它存储在json_encode格式里面。

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

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