2017-01-19 45 views
1

我創建了一個統計頁面,顯示我的網站的每日用戶數量,但是我遇到了問題。我希望每10分鐘更新一次PHP數組,並使用新的用戶數量。不通過網絡連接更新PHP代碼

我的目標是一旦客戶端連接到網頁,它將已經包含一個完整的,最新的用戶數量數組,以便輕鬆製作圖形。

我該怎麼做?

+0

cron job?但爲什麼你可以根據要求獲得統計數據? – nogad

回答

0

如果你正在尋找一些非常簡單和非關鍵的東西(否則我建議使用mySQL表),使用序列化數組並存儲在一個文本文件中。

它可以像這樣工作:

<?php 
class DailyVisitors { 
    protected $today, $statsFilePath, $dailyVisitors; 

    function __construct(){ 
     $this->today = date('Y-m-d'); 

     // A hidden file is more secure, and we use the year and month to prevent the file from bloating up over time, plus the information is now segmented by month 
     $this->statsFilePath = '.dailystats-' . date('Y-m-d'); 

     // Load the file, but if it doesn't exists or we cannot parse it, use an empty array by default 
     $this->dailyVisitors = file_exists(statsFilePath) ? (unserialize(file_get_contents($statsFilePath)) ?: []) : []; 

     // We store the daily visitors as an array where the first element is the visit count for a particular day and the second element is the Unix timestamp of the time it was last updated 
     if(!isset($this->dailyVisitors[$this->today])) $this->dailyVisitors[$this->today] = [0, time()]; 
    } 

    function increment(){ 
     $dailyVisitors[$this->today][0] ++; 
     $dailyVisitors[$this->today][1] = time(); 
     file_put_contents($this->statsFilePath, serialize($this->dailyVisitors))); 
    } 

    function getCount($date = null){ 
     if(!$date) $date = $this->today; // If no date is passed the use today's date 
     $stat = $this->dailyVisitors[$date] ?: [0]; // Get the stat for the date or otherwise use a default stat (0 visitors) 
     return $stat[0]; 
    } 
} 

$dailyVisitors = new DailyVisitors; 

// Increment the counter for today 
$dailyVisitors->increment(); 

// Print today's visit count 
echo "Visitors today: " . $dailyVisitors->getCount(); 

// Print yesterday's visit count 
echo "Visitors yesterday: " . $dailyVisitors->getCount(date('Y-m-d', strtotime('yesterday'))); 

我不知道有任何需要只顯示數據每10分鐘,因爲你已經每有一個新的訪問者反正時間來更新它,數據的反序列化非常快(在單位數毫秒範圍內),但如果出於某種原因需要,您可以僅使用時間戳(每天數組的第二個元素)來確定是否上載單獨的緩存文件只使用時間戳上的模數600(10分鐘)(從Unix紀元開始以秒錶示)來存儲特定日期的訪問計數。