2017-01-19 4 views
1

Я создаю страницу статистики, которая показывает ежедневный подсчет количества пользователей моего веб-сайта, однако я столкнулся с проблемой. Я хотел бы обновить массив PHP каждые ~ 10 минут с новым номером счетчика пользователей.Обновление кода 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 минут, как и вы, чтобы обновить его каждый раз, когда есть новый посетитель в любом случае, и неэтериализация данных довольно быстро (в миллисекундах с одной цифрой), но если по какой-то причине вам нужно, вы можете просто отметку времени (2-й элемент массива каждого дня), чтобы определить, следует ли загружать отдельный файл кеша который хранит только количество посещений за определенный день, используя модуль 600 (10 минут) на отметке времени (который выражается в секундах с эпохи Unix).

Смежные вопросы