[英]PHP unique visitor count without database
我已經完成了一個簡單的PHP訪問者計數,但是它沒有數據庫,只是將其存儲在文本文件中。 但是,即使用戶刷新頁面,視圖計數也會增加。 我正在考慮提出一個獨特的計數器,該計數器僅在上一個會話被破壞並且用戶再次進入該站點之后才會遞增。 但是,我不確定如何實施會議。
PHP代碼:
$handle = fopen("counter.txt", "r");
if(!$handle){
echo "Could not open the file" ;
}
else {
$counter = ( int ) fread ($handle,20) ;
fclose ($handle) ;
$counter++ ;
echo" <p> Visitor Count: ". $counter . " </p> " ;
$handle = fopen("counter.txt", "w" ) ;
fwrite($handle,$counter) ;
fclose ($handle) ;
}
首先,啟動一個會話,以便我們可以跟蹤這是否是用戶第一次在此會話中訪問此站點。
接下來,我們檢查會話“ counter”是否已設置,如果已設置,則不執行任何操作,否則我們用+1更新命中計數器並設置會話“ counter”。
這應該為您完成工作。
<?php
session_start(); // Should always be on top
if(!isset($_SESSION['counter'])) { // It's the first visit in this session
$handle = fopen("counter.txt", "r");
if(!$handle){
echo "Could not open the file" ;
}
else {
$counter = ( int ) fread ($handle,20) ;
fclose ($handle) ;
$counter++ ;
echo" <p> Visitor Count: ". $counter . " </p> " ;
$handle = fopen("counter.txt", "w" ) ;
fwrite($handle,$counter) ;
fclose ($handle) ;
$_SESSION['counter'] = $counter;
}
} else { // It's not the first time, do not update the counter but show the total hits stored in session
$counter = $_SESSION['counter'];
echo" <p> Visitor Count: ". $counter . " </p> " ;
}
?>
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.