2014-02-20 5 views
0

내 웹 사이트에 대한 visitcounter을 프로그래밍하고있어에서PHP - 다음과 같아야합니다 ... TXT 파일

TEXTFILE을 특정 줄을 편집 :

  • 의 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
  • 2222

것 같습니다 파일 이름 끝에 그것을 인쇄 ...

어떻게 올바른 줄에 새 값을 쓸 수 있습니까?

+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-single-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-a-certain-line-of-a-text-file/ http://forums.devshed.com/php-development-5/how-to- 변경 특정 라인 텍스트 파일 -85294.html http://www.linuxquestions.org/questions/programming-9/php-read-file-line-by-line-and-change-a- specific-line-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으로 다시 인코딩하고 텍스트 파일에 저장합니다.