<?php
ob_start();
session_start();
$counter_name = "index.txt";
// Check if a text file exists. If not create one and initialize it to zero.
if (!file_exists($counter_name)) {
$f = fopen($counter_name, "w");
fwrite($f,"0");
fclose($f);
}
// Read the current value of our counter file
$f = fopen($counter_name,"r");
$counterVal = fread($f, filesize($counter_name));
fclose($f);
// Has visitor been counted in this session?
// If not, increase counter value by one
if(!isset($_SESSION['hasVisited'])){
$_SESSION['hasVisited']="yes";
$counterVal++`enter code here`;
$f = fopen($counter_name, "w");
fwrite($f, $counterVal);
fclose($f);
}
?>
我正在使用此代码使用会话计算一个页面上的访问者数量。 但我想在所有其他页面上保留页面计数器。因此,当我将代码复制并粘贴到其他页面时,该值不会增加。它只会在第一页上增加,但不会在我访问的其他页面上增加。什么是可能的解决方案?
答案 0 :(得分:1)
我通过在数据库中存储信息在我的网站上这样做。它比使用txt文件更安全,所以你应该考虑这样做。并且您可以将IP与SESSION一起使用,以便更好地保存记录。使流量日志文件包含在头文件中,该文件将使用请求URI,IP,会话ID /用户ID。
通过使用请求URI,您可以在所有页面上放置单个流量日志记录脚本,以处理您要跟踪的所有不同网页。如果你愿意,我可以添加一些代码示例。
希望这会帮助你!
*/
Define Variables You Want To Store..In this case it is preparing a timestamp, the page (i.e. the $_SERVER['REQUEST_URI']), and the IP
/*
$time = time();
$page = $_SERVER['REQUEST_URI'];
//This is used to sort out the correct IP Address to store //
$client = @$_SERVER['HTTP_CLIENT_IP'];
$forward = @$_SERVER['HTTP_X_FORWARDED_FOR'];
$remote = $_SERVER['REMOTE_ADDR'];
if(filter_var($client, FILTER_VALIDATE_IP)) {
$ip = $client;
} elseif(filter_var($forward, FILTER_VALIDATE_IP)) {
$ip = $forward;
} else {
$ip = $remote;
}
//Use this if you want to see if the data exists already, I usually just store all traffic to make sure people aren't up to anything fishy//
$stmt = $database->prepare("SELECT ID FROM traffic WHERE IP = :IP AND page = :page");
$stmt->bindParam(':IP', $ip);
$stmt->bindParam(':page', $page);
$stmt->execute();
$result = $stmt->FetchALL(PDO::FETCH_ASSOC);
if (!isset($result)) {
$sql = "INSERT INTO traffic (time,IP,page) VALUES (:time, :ip, :page)";
$params = array(
':time' => $time,
':ip' => $ip,
':page' => $page,
);
$stmt = $database->prepare($sql);
$stmt->execute($params);
}
答案 1 :(得分:-1)
您需要在mysql或sqlite或其他数据库服务器中使用以保存名称和访问次数。 您首先需要创建数据库并了解如何使用它。别跑...... 使用TXT文件,您无法到达......