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 / –