私のウェブサイトの毎日のユーザー数を示す統計ページを作成していますが、問題が発生しました。私はPHP配列を〜10分ごとに新しいユーザーカウント数で更新したいと思います。Web経由で接続せずにPHPコードを更新する
クライアントがウェブページに接続すると、グラフを簡単に作成できるように最新の完全なユーザー数の配列が既に含まれています。
どうすればよいですか?
私のウェブサイトの毎日のユーザー数を示す統計ページを作成していますが、問題が発生しました。私はPHP配列を〜10分ごとに新しいユーザーカウント数で更新したいと思います。Web経由で接続せずにPHPコードを更新する
クライアントがウェブページに接続すると、グラフを簡単に作成できるように最新の完全なユーザー数の配列が既に含まれています。
どうすればよいですか?
シリアライズされた配列を使用して、シンプルでクリティカルでないものを探している場合は、フラット・テキスト・ファイルに格納します(そうでなければ、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分ごとにデータを表示する必要がありますかわからない、とデータのシリアライズは非常に高速です(1桁のミリ秒単位で)。何らかの理由で必要な場合は、別々のキャッシュファイルをアップロードするかどうかを判断するタイムスタンプ(毎日の配列の2番目の要素)これはタイムスタンプ上のモジュラス600(10分)(Unixエポックから秒単位で表示されます)を使用して、特定の日の訪問カウントのみを格納します。
cron job?要求に応じて統計情報を取得するのはなぜですか? – nogad