作者:丹愿人常久6688 | 来源:互联网 | 2020-08-25 10:51
PHP对session对象的封装的很好,根据HTTP协议,每个范围网站的访客都可以生成一个唯一的标识符
echo session_id();
//6ed364143f076d136f404ed93c034201
这个就是统计在线人数的关键所在,只有有这个session_id 也就可以区分访问的人了。因为每一个人都不同。
接下来,是怎么把session变量里面的值存到数据库里面去,这里有将介绍另一个函数
bool session_set_save_handler ( callable $open , callable $close , callable $read , callable $write , callable$destroy , callable $gc )
//callable 可随时支取的,请求即付的,随时可偿还的
// open(string $savePath, string $sessionName) 打开连接
//close() 关闭连接
//read(string $sessionId) 对出数据
//write(string $sessionId, string $data) //写入数据
//destroy($sessionId) //删除数据
//gc($lifetime) //垃圾回收函数
注意,上面有几个函数是有参数传入的,你只要表明有传送传入就是的。PHP在执行代码的时候会自动读取
session中对于的参数
接下来就是完成上面五个函数和一个主函数就可以了
session_set_save_handler(
array("session","open"),
array("session","close"),
array("session","read"),
array("session","write"),
array("session","destroy"),
array("session","gc")
);
主函数就这样完成了.
注意:凡是将对象的方法作为参数传递都需要使用这种形式:array(对象, "方法名")
接下来就是每个函数的编写
//链接数据的open
function open($path,$sessname) {
$db = mysql_connect("localhost","root","123456","test");
mysql_select_db("test",$db);
mysql_query("SET NAMES UTF8");
return true;
}
关闭数据可以链接的close
function close(){
$db = mysql_connect("localhost","root","123456","test");
mysql_close($db);
return true;
}
关键函数要开始了,显示读取函数read(),主要,read()函数是有值传进去的,传入的是session_id
function read($sid){
$sql = "select data from session where sid='{$sid}' and card='".self::$card."'";
$query = mysql_query($sql) or die(mysql_error());
$row = mysql_fetch_array($query);
$row>0?$row["data"]:" ";
}
第二个是写入函数,如果数据库里面存在的数据,只要更新时间就可以了,新数据写入
function write($sid,$data)
{
$sql = "select sid from session where sid='{$sid}' and card='".self::$card."'";
$query = mysql_query($sql) or die(mysql_error());
$mtime = time();
$num = mysql_num_rows($query);
if($num){
$sql = "UPDATE session SET data='{$data}', mtime ='{$mtime}'";
}else{
$sql = "INSERT INTO session (sid,data,mtime,ip,card) VALUES('{$sid}','{$data}','".time()."','{$_SERVER['REMOTE_ADDR']}','".self::$card."')";
}
mysql_query($sql);
return true;
}
接下来就是体现PHP回收机制的函数了,两个函数都有参数传入。
function destroy($sid){
$sql = "DELETE FROM session WHERE sid='{$sid}'";
mysql_query($sql) or die(mysql_error());
return true;
}
function gc($max_time){
$max_time = 600;
$sql = "DELETE FROM session WHERE `mtime`<&#39;".(time()-$max_time)."&#39;";
mysql_query($sql) or die(mysql_error());
return true;
}
好了,五个函数都完成了,再就是session表中间读出session的记录条数了。就能准确的统计出正在访问页面的人数。
10分钟没有操作的用户记录将被清空。
精确的通过php实现统计在线人数的方法的代码:
$ftime){
$fline=$fuid.&#39;|&#39;.$ftime."\n";
@fputs($fp,$fline);
}
flock($fp,LOCK_UN);
fclose($fp);
}
}
echo &#39;document.write("&#39;.$total_online.&#39;");&#39;;
以上就是php如何实现和精确统计在线人数功能的详细内容,更多PHP相关知识,请访问PHP教程!
以上就是PHP 实现精确统计在线人数功能的详细内容,更多请关注 第一PHP社区 其它相关文章!