PHP+MySQL统计各地区在线用户数
PHP+MySQL统计各地区在线用户数
当用户访问网站时,更新访问时间,在一定时间内不操作则认为用户不在线。本文中使用PHP记录访客IP,同时通过新浪IP地址接口,获取访客的地理位置(本例只记录省份),并写入mysql表中,即可统计一段时间内的访客总数,也可以查看访客的地区分布。
添加当前IP和更新访问时间 $ip = get_client_ip(); $time = time(); $num = mysql_num_rows(mysql_query("select id from online where ip='$ip'")); if (!$num) { //若online表中没有我的ip,插入ip进行统计 if ($ip != '127.0.0.1') { $api = "http://int.dpool.sina.com.cn/iplookup/iplookup.php?format=json&ip=$ip"; $json = file_get_contents($api); $arr = json_decode($json, true); $province = $arr['province']; } else { $province = "本地"; } mysql_query("insert into online (ip,province,addtime) values ('$ip','$province','$time')"); } else { //否则更新我的ip时间 mysql_query("update online set addtime='$time' where ip='$ip'"); } 统计2小时内在线用户数 $t = $time - 3600 * 2; //2小时内的 $where = " WHERE addtime >= " . $t . ""; $totalOnline = mysql_num_rows(mysql_query("select id from online " . $where . "")); 获取用户ip列表 $sql = "select province,count(*) as total from online " . $where . " group by province order by total desc"; $list = array(); $query = mysql_query($sql); $str = ''; while ($row = mysql_fetch_array($query)) { $str .= "<li><span>" . $row['total'] . "</span>" . $row['province'] . "</li>"; } 最后显示在线人数$totalOnline,和地区统计在线人数列表$str <div id="total">在线人数:<span id="onlinenum"><?php echo $totalOnline; ?></span></div> <ul id="onlinelist"> <?php echo $str; ?> </ul>下载地址:
此处内容已隐藏,评论后刷新即可查看!