Home>Article>Backend Development> PHP+Mysql+jQuery counts the current number of online users

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

墨辰丷
墨辰丷 Original
2018-06-06 17:45:10 1685browse

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.

当前在线:

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}

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 '0', PRIMARY KEY (`id`) ) ENGINE=MyISAM DEFAULT CHARSET=utf8;

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('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?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 + "
  • "+array['total']+""+array['province']+"
  • "; }); $("#onlinelist").html(str); }); },function(){ $("#onlinelist").slideUp("fast"); }); });

    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!

    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