php对session对象的封装的很好,根据http协议,每个范围网站的访客都可以生成一个唯一的标识符

echo session_id();

//6ed364143f076d136f404ed93c034201<br />

  

这个就是统计在线人数的关键所在,只有有这个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`<'".(time()-$max_time)."'";

  mysql_query($sql) or die(mysql_error());

  return true;

}

  

好了,五个函数都完成了,再就是session表中间读出session的记录条数了。就能准确的统计出正在访问页面的人数。

10分钟没有操作的用户记录将被清空。

精确的通过php实现统计在线人数的方法的代码:

<?php

$filename='online.txt';//数据文件

$cookiename='vgotcn_onlinecount';//cookie名称

$onlinetime=600;//在线有效时间,单位:秒 (即600等于10分钟)

    

$online=file($filename);

//php file() 函数把整个文件读入一个数组中。与 file_get_contents() 类似,不同的是 file() 将文件作为一个数组返回。数组中的每个单元都是文件中相应的一行,包括换行符在内。如果失败,则返回 false

$nowtime=$_server['request_time'];

$nowonline=array();

//得到仍然有效的数据

foreach($online as $line){

  $row=explode('|',$line);

  $sesstime=trim($row[1]);

  if(($nowtime - $sesstime)<=$onlinetime){//如果仍在有效时间内,则数据继续保存,否则被放弃不再统计

    $nowonline[$row[0]]=$sesstime;//获取在线列表到数组,会话id为键名,最后通信时间为键值

  }

}

/*

@创建访问者通信状态

使用cookie通信

cookie 将在关闭浏览器时失效,但如果不关闭浏览器,此 cookie 将一直有效,直到程序设置的在线时间超时

*/

if(isset($_cookie[$cookiename])){//如果有cookie即并非初次访问则不添加人数并更新通信时间

  $uid=$_cookie[$cookiename];

}else{//如果没有cookie即是初次访问

  $vid=0;//初始化访问者id

  do{//给用户一个新id

    $vid++;

    $uid='u'.$vid;

  }while(array_key_exists($uid,$nowonline));

  setcookie($cookiename,$uid);

}

$nowonline[$uid]=$nowtime;//更新现在的时间状态

//统计现在在线人数

$total_online=count($nowonline);

//写入数据

if($fp=@fopen($filename,'w')){

  if(flock($fp,lock_ex)){

    rewind($fp);

    foreach($nowonline as $fuid=>$ftime){

      $fline=$fuid.'|'.$ftime."\n";

      @fputs($fp,$fline);

    }

    flock($fp,lock_un);

    fclose($fp);

  }

}

echo 'document.write("'.$total_online.'");';

  

以上就是php实现统计在线人数的方法的详细内容

更多内容请访问

怎么从一名码农成为架构师的必看知识点:目录大全(持续更新)50w年薪挑战