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

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

Jun 06, 2018 pm 05:45 PM

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!

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

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

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

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Explain JSON Web Tokens (JWT) and their use case in PHP APIs. Explain JSON Web Tokens (JWT) and their use case in PHP APIs. Apr 05, 2025 am 12:04 AM

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,

How does session hijacking work and how can you mitigate it in PHP? How does session hijacking work and how can you mitigate it in PHP? Apr 06, 2025 am 12:02 AM

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.

Describe the SOLID principles and how they apply to PHP development. Describe the SOLID principles and how they apply to PHP development. Apr 03, 2025 am 12:04 AM

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? How to debug CLI mode in PHPStorm? Apr 01, 2025 pm 02:57 PM

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 permissions of unixsocket after system restart? How to automatically set permissions of unixsocket after system restart? Mar 31, 2025 pm 11:54 PM

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...

Explain late static binding in PHP (static::). Explain late static binding in PHP (static::). Apr 03, 2025 am 12:04 AM

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.

How to send a POST request containing JSON data using PHP's cURL library? How to send a POST request containing JSON data using PHP's cURL library? Apr 01, 2025 pm 03:12 PM

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�...

See all articles