php ajax网站浏览统计功能的简单实现第1/2页

问题描述:

这个功能应该是很多网站都需要的,这里仅仅实现了一个基于文件的简易版本,数据库的版本请自行参考实现,我这里实现的功能很不完善,比如未过滤是否为同一访客,是否为同一IP等等,这里仅仅是给大家提供一个参考.


对于这个文件中使用的连接设置ctl参数见[ajax实时任务提示功能的实现]中的/ucren/taskofpig/appConfig.php
文件的controllerAccessor 设置.

//各位注意目录使用Serv这是这个它是一个插件,(*^__^*) 嘻嘻……
/ucren/taskofpig/Serv/VisiterService.php
<?php
class Serv_VisiterService
{
var $log_file ;
function Serv_VisiterService($log_file) //必须传递日志文件路径进来
{
$this->log_file = $log_file ;
}
function addVisiter()
{
$newVisiter = array(
'guest_ip' => $_SERVER["REMOTE_ADDR"] ,
'time' => date('Y-m-d H:i:s') ,
'guest_port' => $_SERVER["REMOTE_PORT"] ,
'request_uri' => $_SERVER["REQUEST_URI"] ,
'accept_lang' => $_SERVER["HTTP_ACCEPT_LANGUAGE"] ,
'os_info' => $_SERVER["HTTP_USER_AGENT"]
);
//$fp = fopen("{$this->prj_dir}/_log/visiter.dat","a+b");
$fp = fopen($this->log_file,"a+b");
fwrite($fp,serialize($newVisiter));
//写入换行符--LINUX是\n windows是 \r\n ,这里要求注意 单引号与双引号的区别
fwrite($fp,"\r\n");//单引号不转义
fclose($fp);
}
function getVisiters()
{
if (!file_exists($this->log_file))
return null ;
$visiterArr_tmp = file($this->log_file) ;//将文件读入数组中
foreach($visiterArr_tmp as $visiter)
{
$visiterArr[] = unserialize($visiter) ;
}
return $visiterArr ;
}
}
?>

这里在上文中新建的/ucren/taskofpig/Controller/Default.php文件中添加如下代码,完整代码如下
<?php
FLEA::loadFile('Serv_VisiterService.php',true) ;//加载访客统计插件代码到程序中
class Controller_Default extends FLEA_Controller_Action
{
var $prj_dir ;var $visiters ;var $smarty ;
function actionIndex(){
$this->prj_dir = '.' ;
$this->smarty = $this->_getView(); //获取smarty模板对象,在/ucren/taskofpig/appConfig.php中配置
$this->visiters = new Serv_VisiterService("{$this->prj_dir}/log/visiter.dat") ;
//添加访客
$this->visiters->addVisiter();
redirect(url('TaskOfPig'),0); //停顿0秒后,重定向到index.php?ctl=TaskOfPig
}
function actionVisiters() //访客统计列表
{
$this->smarty->assign('sitename','任务计划表 -- 生气猪') ;
$this->smarty->assign('opname','访客统计') ;
$rows = $this->visiters->getVisiters();
$this->smarty->assign('rowSet',$rows);
$this->_showPage('taskofpig.visiterlist.html');
}
}
?>

/ucren/taskofpig/tpl/taskofpig.visiterlist.html
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title><%$sitename%> -- <%$opname%></title>
</head>
<body>
<hr>
<table width="100%" border="1" cellspacing="1" bgcolor="#cfdadc">
<tr bgcolor="#e8edec" align="center">
<td><b>访问次序</b></td>
<td><b>IP地址</b></td>
<td><b>日期/时间</b></td>
<td><b>客户机信息</b></td>
</tr>
<%section name=rowIndex loop=$rowSet%>
<tr align="center">
<%*注意怎么获取rowIndex的语法*%>
<td><%$smarty.section.rowIndex.index%></td>
<td><%$rowSet[rowIndex].guest_ip%></td>
<td><%$rowSet[rowIndex].time%></td>
<td><%$rowSet[rowIndex].os_info%></td>
</tr>
<%/section%>
</table>
</body>
</html>
这样就可以在浏览器中敲入
http://localhost/ucren/taskofpig 进入,缺省将在后台加入访问者信息,如果你敲入
http://localhost/ucren/taskofpig/index.php?act=visiters
可以进入来访者信息查看页面,例子截图如下