Home  >  Article  >  Backend Development  >  PHP statistics of the number of currently online users explained with examples, current online examples explained_PHP tutorial

PHP statistics of the number of currently online users explained with examples, current online examples explained_PHP tutorial

WBOY
WBOYOriginal
2016-07-12 09:07:13994browse

Explanation of PHP statistics on the number of current online users, explanation of current online users

Usually, when a visitor visits a website, the page records the user's cookie information. When the cookie expires, it is considered that the user is no longer available. online. In this article, we use PHP to record the visitor's IP, and record the cookie and expiration time on the client. At the same time, we obtain the visitor's geographical location through the Sina IP address interface (this example only records the province), and write it into the mysql table for statistics. The total number of visitors within a period of time, and the regional distribution of visitors can also be viewed.

HTML
We place a div#total on the page that displays the current number of people online and a list #onlinelist that displays the regional distribution of visitors. By default, we place an animated picture with loading in the list. Later we use jQuery to control when the mouse slides over Show detailed list.

<div class="demo"> 
  <div id="total">当前在线:<span id="onlinenum"></span></div> 
  <ul id="onlinelist"> 
    <li><img src="loader.gif"></li> 
  </ul> 
</div> 

CSS
We use CSS to render the display effect. In order not to make our example ugly, in the code below, we use CSS3. Times are advancing, so it is recommended to use modern browsers to preview the effect.

.demo{width:150px; margin:20px auto; font-size:14px} 
#total{padding:6px 10px; background:#090 url(arr.png) no-repeat right top; color:#fff; 
cursor:pointer; -moz-border-radius:5px; -webkit-border-radius:5px; border-radius:5px; 
-moz-box-shadow:0 0 3px #ccc; -webkit-box-shadow:0 0 3px #ccc;box-shadow:0 0 3px #ccc;} 
#onlinelist{background:#f7f7f7; border:1px solid #d3d3d3; display:none; -moz-border-radius:5px; 
-webkit-border-radius:5px; border-radius:5px; -moz-box-shadow:0 0 3px #ccc; 
-webkit-box-shadow:0 0 3px #ccc;box-shadow:0 0 3px #ccc;} 
#onlinelist li{height:20px; line-height:20px;padding:4px 6px;border-bottom:1px dotted #d9d9d9} 
#onlinelist li span{float:right} 
#onlinelist li:hover{background:#fff} 

Mysql
We need to prepare a data table online to record visitor IP, region and access time. The entire sample statistical process relies on this table, whose structure is as follows:

CREATE TABLE IF NOT EXISTS `online` ( 
 `id` int(11) NOT NULL AUTO_INCREMENT, 
 `ip` varchar(30) NOT NULL, 
 `province` varchar(64) NOT NULL, 
 `addtime` int(10) NOT NULL DEFAULT '0', 
 PRIMARY KEY (`id`) 
) ENGINE=MyISAM DEFAULT CHARSET=utf8; 

PHP
online.php is used to record visitor information, including IP address and region. First, check whether there is a visitor IP record in the data table. If so, only update the access time. Otherwise, obtain the user's province and region, and insert the user's IP, that is, the province and region into the table. Here, you can determine whether there is a cookie record for the visitor. If it does not exist, request the visitor's regional information from the Sina IP address database and set the cookie value and expiration time. Finally, we delete the expired records in the table, count the total number of records and output them. Please see the code comments for details.

include_once('connect.php'); //连接数据库 
 
$ip = get_client_ip(); //获取客户端IP 
$time = time(); 
//查询表中是否有ip为当前访客IP的记录 
$query = mysql_query("select id from online where ip='$ip'"); 
if(!mysql_num_rows($query)){//如果不存在访客IP 
  if($_COOKIE['geoData']){//如果存在cookie,则获取用户的区域 
    $province = $_COOKIE['geoData']; //区域(省份) 
  }else{ 
    $api = "http://int.dpool.sina.com.cn/iplookup/iplookup.php&#63;format=json&ip=$ip"; 
    $json = file_get_contents($api);//
    $arr = json_decode($json,true);//解析json 
    $province = $arr['province'];//获取省份 
    setcookie('geoData',$province,$time+600); //设置cookie,设置过期时间为10分钟 
  } 
  //将访客信息插入到数据表中 
  mysql_query("insert into online (ip,province,addtime) values ('$ip','$province','$time')"); 
}else{//如果存在,则更新该用户访问时间 
  mysql_query("update online set addtime='$time' where ip='$ip'"); 
} 
//删除已过期的记录 
$outtime = $time-600; 
mysql_query("delete from online where addtime<$outtime"); 
//统计总记录数,即在线用户数 
list($totalOnline) = mysql_fetch_array(mysql_query("select count(*) from online")); 
echo $totalOnline;//输出在线总数 
mysql_close(); 

The function get_client_ip() is used to obtain the user’s real IP.

function get_client_ip() { 
  if (getenv("HTTP_CLIENT_IP") && strcasecmp(getenv("HTTP_CLIENT_IP"), "unknown")) 
    $ip = getenv("HTTP_CLIENT_IP"); 
  else if (getenv("HTTP_X_FORWARDED_FOR") && strcasecmp(getenv("HTTP_X_FORWARDED_FOR"), 
"unknown")) 
    $ip = getenv("HTTP_X_FORWARDED_FOR"); 
  else if (getenv("REMOTE_ADDR") && strcasecmp(getenv("REMOTE_ADDR"), "unknown")) 
    $ip = getenv("REMOTE_ADDR"); 
  else if (isset ($_SERVER['REMOTE_ADDR']) && 
$_SERVER['REMOTE_ADDR'] && strcasecmp($_SERVER['REMOTE_ADDR'], "unknown")) 
    $ip = $_SERVER['REMOTE_ADDR']; 
  else 
    $ip = "unknown"; 
  return ($ip); 
} 

geo.php is used to count the distribution of the number of visitors in each province (region). Just query the database and sort by province. Note that we will output the final data set in the form of JSON to facilitate front-end ajax interaction.

include_once('connect.php');//连接数据库 
//查询区域统计 
$sql = "select province,count(*) as total from online group by province order by total desc"; 
$result = mysql_query($sql); 
while($row=mysql_fetch_array($result)){ 
  $list[] = array( 
    'province' => $row['province'], 
    'total' => $row['total'] 
  );  
} 
echo json_encode($list);//以json格式输出 

jQuery
What the front-end page needs to do is to display the total number of visitors when the page is loaded, that is, use ajax to request online.php. Then when the mouse slides over the statistics arrow, geo.php is requested through ajax to obtain the number of online people in each region and province, and the effect is displayed in a drop-down manner.

$(function(){ 
  $("#onlinenum").load("online.php"); 
   
  $(".demo").hover(function(){ 
    $("#onlinelist").slideDown("fast"); 
    var str = ''; 
    $.getJSON("geo.php",function(json){ 
      $.each(json,function(index,array){ 
        str = str + "<li><span>"+array['total']+"</span>"+array['province']+"</li>"; 
      }); 
      $("#onlinelist").html(str); 
    }); 
  },function(){ 
    $("#onlinelist").slideUp("fast"); 
  }); 
}); 

Finally, this example has dependencies, so don’t forget to load the jquery library first on the page. The current version is jquery-1.9.1.

The content is very exciting and rich. I just share it with you. I hope it will be helpful to everyone's learning.

www.bkjia.comtruehttp: //www.bkjia.com/PHPjc/1063219.htmlTechArticleExplanation of the number of current online users in PHP statistics. Explanation of the current online users. Usually, when a visitor visits the website, the page records the user Cookie information, when the cookie expires, it is considered that the user is not online. ...
Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn