【发布时间】:2014-02-20 08:46:41
【问题描述】:
我正在为我的网站编写访问计数器...
文本文件应如下所示:
- 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,并将其打印在文件末尾...
如何将新值写入正确的行?
【问题讨论】:
-
试试this
-
您可以在 texfile 中存储一个包含您的数据的 json 数组。每次将值存储在数组中并将其编码为 json 并存储在文本文件中。当你想找回它。读取数组中的文件解码json并使用它。