簡體   English   中英

網站不同頁面上的頁面計數器

[英]page counter on different pages of website

<?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); 
}
?>

我正在使用此代碼來計算使用會話的一頁上的訪問者數量。 但是我也想在所有其他頁面上保持頁面計數。 因此,當我將代碼復制並粘貼到其他頁面時,該值不會增加。 它只會在首頁上增加,而不會在我訪問的其他頁面上增加。 有什么可能的解決方案?

我在網站上通過將信息存儲在數據庫中來做到這一點。 它比使用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);
}

您需要在mysql或sqlite或其他數據庫服務器中使用,以保存名稱和訪問次數。 您首先需要創建數據庫並學習如何使用它。 不要運行...。使用TXT文件,您將無法到達...

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM