Thống kê truy cập đơn giản bằng file PHP
Dưới đây là code thống kê truy cập đơn giản.
Tạo tập tin stats.php:
define('ROOT', dirname(dirname(__FILE__)) . DIRECTORY_SEPARATOR);define('URI',$_SERVER['REQUEST_URI']);
$ip = $_SERVER['REMOTE_ADDR'];
function online(){
global $ip;
$file = ROOT . 'counter/online.log';
$data = file_get_contents($file);
if(count(explode($ip,$data)) < 2) $data .= "[email protected]".date('U')."@".URI."\r\n";
$lines = explode("\r\n",$data);
foreach($lines as $a){
if(count(explode($ip,$a)) > 1) $data = str_replace($a, $ip.'@'.date('U').'@'.URI, $data);
elseif(!empty($a) && explode('@',$a)[1] < date('U') - 15 * 60) $data = str_replace($a."\r\n", '', $data);
}
$online = count(explode("\r\n",$data))-1;
file_put_contents($file, $data);
return $online;
}
function today(){
$file = ROOT . 'counter/count.txt';
$data = file_get_contents($file);
$today = explode('@',$data)[0];
$td = explode('|',$today);
$total = explode('@',$data)[1];
$total++;
if($td[1]==date('dmY')) $tday = $td[0]+1;
else $tday = 1;
$today = $tday.'|'.date('dmY');
file_put_contents($file,$today.'@'.$total);
return $tday.'/'.$total;
}
Tạo các file, thư mục sau (cùng phân cấp thư mục):
stats.php
counter/
-------------count.txt
-------------online.log
Cách dùng:
require('stats.php');echo 'Online: ' . online();
echo '<br/>Truy cập hôm nay / tổng: ' . today();
Lưu ý: this is function.
Nguồn: hanhphucao - Phonho.net