Table of Contents
PHP+MySQL+jQuery统计当前在线用户数" >PHP+MySQL+jQuery统计当前在线用户数
Home php教程 php手册 PHP ajax 统计当前在线用户数程序代码

PHP ajax 统计当前在线用户数程序代码

May 25, 2016 pm 04:55 PM
include select

本文章来给大家介绍PHP ajax 统计当前在线用户数程序代码,有需要的朋友可参考。

我们要统计在一段时间内访问站点的人数,有多种解决方案,你可以使用cookie,session结合文本或者数据库来记录用户访问数。本文将使用PHP,结合Mysql以及jQuery,展示一个统计在线人数以及访客地区分布的示例。

通常,当访客访问网站时,页面记录用户的cookie信息,当cookie过期即认为用户不在线。本文中我们使用PHP记录访客IP,并在客户端记录cookie及过期时间,同时通过新浪IP地址接口,获取访客的地理位置(本例只记录省份),一并写入mysql表中,即可统计一段时间内的访客总数,也可以查看访客的地区分布。

HTML

我们在页面上放置一个显示当前在线人数的div#total以及一个用于展示访客地区分布的列表#onlinelist,默认我们在列表中放置一张与加载动画图片,后面我们用jQuery控制当鼠标滑向时展示详细列表。

 代码如下 复制代码

 
      
当前在线:
 
    
     
            
  • PHP ajax 统计当前在线用户数程序代码
  •  
        
 
 

CSS

我们用CSS来渲染显示效果,为了就是不让我们的示例很难看,下面的代码中,我们使用了CSS3,时代在进步啊,所以建议使用现代浏览器预览效果。

.

 代码如下 复制代码
demo{width:150px; margin:20px auto; font-size:14px} 
#total{padding:6px 10px; background:#090 url(http://pic1.phprm.com/2013/05/02/arr.jpg) 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

我们要准备一张数据表online,用来记录访客IP、地区及访问时间。整个示例统计过程都依赖这张表,其结构如下:

 代码如下 复制代码

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用来记录访客信息,包括IP地址和地区。首先检测数据表中是否有访客IP记录,如果有,则只更新访问时间,否则,获取用户省份区域,并将用户IP即省份区域插入到表中。在此,可以判断是否存在访客的cookie记录,如果不存在则向新浪IP地址库请求获取访客的区域信息,并设置cookie值和过期时间。最后,我们删除表中已经过期的记录,统计总记录数并输出,详细请看代码注释。

 代码如下 复制代码

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);//调用新浪IP地址库 
        $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//统计总记录数,即在线用户数 
list($totalOnline) = mysql_fetch_array(mysql_query("select count(*) from online"));  
echo $totalOnline;//输出在线总数 
mysql_close(); 

 

关于新浪IP地址库的调用,您也可以参阅helloweba.com文章根据IP定位用户所在城市信息的介绍。

函数get_client_ip()用来获取用户真实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用来统计各省份(区域)访客人数分布。通过查询数据库,并按省份分组排序即可,注意我们将最终的数据集以JSON的形式输出,便于前端ajax交互。

 代码如下 复制代码

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

前端页面需要做的是,页面加载时展示访客总数,即使用ajax请求online.php即可。然后当鼠标滑向统计箭头时,通过ajax请求geo.php获取各区域省份的在线人数,并以下拉的方式展现效果。

 代码如下 复制代码

$(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"); 
        }); 
    }); 

    完整实例

     代码如下 复制代码





    PHP+MySQL+jQuery统计当前在线用户数






     

    PHP+MySQL+jQuery统计当前在线用户数


     

       
    当前在线:

       

           
    • PHP ajax 统计当前在线用户数程序代码

    •    

     

     





     




    文章链接:

    随便收藏,请保留本文地址!

    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)

    What is the difference between php include and include_once What is the difference between php include and include_once Mar 22, 2023 am 10:38 AM

    When we write web pages using PHP, sometimes we need to include code from other PHP files in the current PHP file. At this time, you can use the include or include_once function to implement file inclusion. So, what is the difference between include and include_once?

    Asynchronous processing method of Select Channels Go concurrent programming using golang Asynchronous processing method of Select Channels Go concurrent programming using golang Sep 28, 2023 pm 05:27 PM

    Asynchronous processing method of SelectChannelsGo concurrent programming using golang Introduction: Concurrent programming is an important area in modern software development, which can effectively improve the performance and responsiveness of applications. In the Go language, concurrent programming can be implemented simply and efficiently using Channels and Select statements. This article will introduce how to use golang for asynchronous processing methods of SelectChannelsGo concurrent programming, and provide specific

    How to hide the select element in jquery How to hide the select element in jquery Aug 15, 2023 pm 01:56 PM

    How to hide the select element in jquery: 1. hide() method, introduce the jQuery library into the HTML page, you can use different selectors to hide the select element, the ID selector replaces the selectId with the ID of the select element you actually use; 2. css() method, use the ID selector to select the select element that needs to be hidden, use the css() method to set the display attribute to none, and replace selectId with the ID of the select element.

    How to implement change event binding of select elements in jQuery How to implement change event binding of select elements in jQuery Feb 23, 2024 pm 01:12 PM

    jQuery is a popular JavaScript library that can be used to simplify DOM manipulation, event handling, animation effects, etc. In web development, we often encounter situations where we need to change event binding on select elements. This article will introduce how to use jQuery to bind select element change events, and provide specific code examples. First, we need to create a dropdown menu with options using labels:

    What is the reason why Linux uses select? What is the reason why Linux uses select? May 19, 2023 pm 03:07 PM

    Because select allows developers to wait for multiple file buffers at the same time, it can reduce IO waiting time and improve the IO efficiency of the process. The select() function is an IO multiplexing function that allows the program to monitor multiple file descriptors and wait for one or more of the monitored file descriptors to become "ready"; the so-called "ready" state is Refers to: the file descriptor is no longer blocked and can be used for certain types of IO operations, including readable, writable, and exceptions. select is a computer function located in the header file #include. This function is used to monitor file descriptor changes—reading, writing, or exceptions. 1. Introduction to the select function. The select function is an IO multiplexing function.

    How to use the select syntax of mysql How to use the select syntax of mysql Jun 01, 2023 pm 07:37 PM

    1. Keywords in SQL statements are not case-sensitive. SELECT is equivalent to SELECT, and FROM is equivalent to from. 2. To select all columns from the users table, you can use the symbol * to replace the column name. Syntax--this is a comment--query out [all] data from the [table] specified by FEOM. * means [all columns] SELECT*FROM--query out the specified data from the specified [table] from FROM Data of column name (field) SELECT column name FROM table name instance--Note: Use English commas to separate multiple columns selectusername, passwordfrom

    Implement Select Channels Go concurrent programming performance optimization through golang Implement Select Channels Go concurrent programming performance optimization through golang Sep 27, 2023 pm 01:09 PM

    Implementing SelectChannels through golang Performance optimization of Go concurrent programming In the Go language, it is very common to use goroutine and channel to implement concurrent programming. When dealing with multiple channels, we usually use select statements for multiplexing. However, in the case of large-scale concurrency, using select statements may cause performance degradation. In this article, we will introduce some implementations of select through golang

    Select Channels Go concurrent programming for reliability and robustness using golang Select Channels Go concurrent programming for reliability and robustness using golang Sep 28, 2023 pm 05:37 PM

    SelectChannels for Reliability and Robustness Using Golang Introduction to Concurrent Programming: In modern software development, concurrency has become a very important topic. Using concurrent programming can make programs more responsive, utilize computing resources more efficiently, and be better able to handle large-scale parallel computing tasks. Golang is a very powerful concurrent programming language. It provides a simple and effective way to implement concurrent programming through go coroutines and channel mechanisms.

    See all articles