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
文件名,並將其打印在文件末尾...
如何在正確的行中寫入新值?
嘗試[this](http://stackoverflow.com/questions/7859840/php-fetching-a-txt-file-and-editing-a-single-line?rq=1) –
您可以存儲在您的texfile一個包含你的數據的json數組。每次將值存儲在數組中並將其編碼到json中並存儲到文本文件中。當你想檢索它。讀數組中的文件解碼json並使用它。 –
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 / –