PHP+Mysql+jQuery counts the current number of online users
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>
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 + "<li><span>"+array['total']+"</span>"+array['province']+"</li>"; }); $("#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!

Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics

Alipay PHP...

JWT is an open standard based on JSON, used to securely transmit information between parties, mainly for identity authentication and information exchange. 1. JWT consists of three parts: Header, Payload and Signature. 2. The working principle of JWT includes three steps: generating JWT, verifying JWT and parsing Payload. 3. When using JWT for authentication in PHP, JWT can be generated and verified, and user role and permission information can be included in advanced usage. 4. Common errors include signature verification failure, token expiration, and payload oversized. Debugging skills include using debugging tools and logging. 5. Performance optimization and best practices include using appropriate signature algorithms, setting validity periods reasonably,

Session hijacking can be achieved through the following steps: 1. Obtain the session ID, 2. Use the session ID, 3. Keep the session active. The methods to prevent session hijacking in PHP include: 1. Use the session_regenerate_id() function to regenerate the session ID, 2. Store session data through the database, 3. Ensure that all session data is transmitted through HTTPS.

The application of SOLID principle in PHP development includes: 1. Single responsibility principle (SRP): Each class is responsible for only one function. 2. Open and close principle (OCP): Changes are achieved through extension rather than modification. 3. Lisch's Substitution Principle (LSP): Subclasses can replace base classes without affecting program accuracy. 4. Interface isolation principle (ISP): Use fine-grained interfaces to avoid dependencies and unused methods. 5. Dependency inversion principle (DIP): High and low-level modules rely on abstraction and are implemented through dependency injection.

How to debug CLI mode in PHPStorm? When developing with PHPStorm, sometimes we need to debug PHP in command line interface (CLI) mode...

How to automatically set the permissions of unixsocket after the system restarts. Every time the system restarts, we need to execute the following command to modify the permissions of unixsocket: sudo...

Static binding (static::) implements late static binding (LSB) in PHP, allowing calling classes to be referenced in static contexts rather than defining classes. 1) The parsing process is performed at runtime, 2) Look up the call class in the inheritance relationship, 3) It may bring performance overhead.

Sending JSON data using PHP's cURL library In PHP development, it is often necessary to interact with external APIs. One of the common ways is to use cURL library to send POST�...
