PHP-编辑txt文件中的特定行
我正在为我的网站编程一个visitcounter 文本文件应如下所示:PHP-编辑txt文件中的特定行,php,cookies,counter,Php,Cookies,Counter,我正在为我的网站编程一个visitcounter 文本文件应如下所示: 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_S
- 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
,并在文件末尾打印出来
如何在正确的行中写入新值?这是另一种将数据存储在经常更改的文本文件中的方法
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_编码格式
每当我们想要更新特定的页面计数时。读取文件中写入的json,在php数组中对其进行解码,如果页面存在,则更新计数;如果数组中不存在页面索引,则使用新页面分配1
然后,我们再次将其编码为json并存储在文本文件中。尝试将包含数据的json数组存储在文本文件中。每次都将值存储在数组中,用json编码并存储在文本文件中。当你想要取回它的时候。读取文件解码数组中的json并使用它。