PHP+Mysql+jQuery counts the current number of online users

墨辰丷
Release: 2023-03-30 10:22:02
Original
1755 people have browsed it

This article mainly introduces PHP Mysql jQuery to count the current number of online users. Interested friends can refer to it. I hope it will be helpful to everyone.

HTML

We place a p#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 are in the list Place a picture with loading animation, and later we use jQuery to control the detailed list to be displayed when the mouse slides over.

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

CSS
We use CSS to render the display effect. In order not to make our example ugly, in the following code, we use CSS3. Times are progressing. Therefore, it is recommended to use a modern browser 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}
Copy after login

Mysql
We need to prepare a data table online to record visitor IP, region and access time. The entire sample statistics 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 &#39;0&#39;, 
 PRIMARY KEY (`id`) 
) ENGINE=MyISAM DEFAULT CHARSET=utf8;
Copy after login

PHPonline.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(&#39;connect.php&#39;); //连接数据库 
 
$ip = get_client_ip(); //获取客户端IP 
$time = time(); 
//查询表中是否有ip为当前访客IP的记录 
$query = mysql_query("select id from online where ip=&#39;$ip&#39;"); 
if(!mysql_num_rows($query)){//如果不存在访客IP 
  if($_COOKIE[&#39;geoData&#39;]){//如果存在cookie,则获取用户的区域 
    $province = $_COOKIE[&#39;geoData&#39;]; //区域(省份) 
  }else{ 
    $api = "http://int.dpool.sina.com.cn/iplookup/iplookup.php?format=json&ip=$ip"; 
    $json = file_get_contents($api);//
    $arr = json_decode($json,true);//解析json 
    $province = $arr[&#39;province&#39;];//获取省份 
    setcookie(&#39;geoData&#39;,$province,$time+600); //设置cookie,设置过期时间为10分钟 
  } 
  //将访客信息插入到数据表中 
  mysql_query("insert into online (ip,province,addtime) values (&#39;$ip&#39;,&#39;$province&#39;,&#39;$time&#39;)"); 
}else{//如果存在,则更新该用户访问时间 
  mysql_query("update online set addtime=&#39;$time&#39; where ip=&#39;$ip&#39;"); 
} 
//删除已过期的记录 
$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();
Copy after login

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[&#39;REMOTE_ADDR&#39;]) && 
$_SERVER[&#39;REMOTE_ADDR&#39;] && strcasecmp($_SERVER[&#39;REMOTE_ADDR&#39;], "unknown")) 
    $ip = $_SERVER[&#39;REMOTE_ADDR&#39;]; 
  else 
    $ip = "unknown"; 
  return ($ip); 
}
Copy after login

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(&#39;connect.php&#39;);//连接数据库 
//查询区域统计 
$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( 
    &#39;province&#39; => $row[&#39;province&#39;], 
    &#39;total&#39; => $row[&#39;total&#39;] 
  );  
} 
echo json_encode($list);//以json格式输出
Copy after login

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 = &#39;&#39;; 
    $.getJSON("geo.php",function(json){ 
      $.each(json,function(index,array){ 
        str = str + "<li><span>"+array[&#39;total&#39;]+"</span>"+array[&#39;province&#39;]+"</li>"; 
      }); 
      $("#onlinelist").html(str); 
    }); 
  },function(){ 
    $("#onlinelist").slideUp("fast"); 
  }); 
});
Copy after login

Summary: The above is the entire content of this article, I hope it will be helpful to everyone's study.

Related recommendations:

PHP modular installation detailed step-by-step tutorial

##PHP implements WeChat official account to automatically send red envelope API

Detailed explanation of methods and examples of php file operations

The above is the detailed content of PHP+Mysql+jQuery counts the current number of online users. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template