PHP ajax program code for counting the current number of online users

Source: Internet
Author: User
Tags json

We want to count the number of visitors to the site within a period of time. There are multiple solutions. You can use cookies, sessions, and text or databases to record the number of user tokens. This article uses PHP, Mysql, and jQuery to show an example of how to count the number of online users and the distribution of visitor regions.

Generally, when a visitor accesses a website, the page records the cookie information of the user. When the cookie expires, the user is considered offline. In this article, we use PHP to record the visitor's IP address, record the cookie and expiration time on the client, and obtain the geographic location of the visitor through the Sina IP address interface (in this example, only the province is recorded ), write the data into the mysql table to count the total number of visitors within a period of time. You can also view the regional distribution of visitors.

HTML

On the page, we place a div # total that shows the current number of online users and a list that shows the distribution of visitor regions # onlinelist. By default, we place an animation image in the list and load it, next we will use jQuery to display the detailed list when the mouse slides.

The code is as follows: Copy code

<Div class = "demo">
<Div id = "total"> online: <span id = "onlinenum"> </span> </div>
<Ul id = "onlinelist">
<Li> </li>
</Ul>
</Div>

CSS

We use CSS to render the display effect, in order to prevent our example from getting ugly. In the following code, we use CSS3, and the times are improving. Therefore, we recommend that you use a modern browser to preview the display effect.

.

The code is as follows: Copy code
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

Prepare a data table online to record the visitor's IP address, region, and access time. The entire statistical process in this example depends on this table. Its structure is as follows:

The code is as follows: Copy code

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 is used to record visitor information, including IP addresses and regions. First, check whether there are visitor IP records in the data table. If yes, only the access time is updated. Otherwise, obtain the user's province region and insert the user's IP address, namely, the province region, to the table. Here, you can determine whether there is a visitor's cookie record. If not, request the Sina IP address library to obtain the visitor's region information 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. For details, see the code comment.

The code is as follows: Copy code

Include_once ('connect. Php'); // connect to the database
 
$ Ip = get_client_ip (); // Obtain the client IP address
$ Time = time ();
// Query whether the ip address is the current visitor IP address.
$ Query = mysql_query ("select id from online where ip = '$ IP '");
If (! Mysql_num_rows ($ query) {// if no visitor IP address exists
If ($ _ COOKIE ['geodata']) {// if a cookie exists, obtain the user's region
$ Province = $ _ COOKIE ['geodata']; // region (province)
} Else {
$ Api = "http://int.dpool.sina.com.cn/iplookup/iplookup.php? Format = json & ip = $ ip ";
$ Json = file_get_contents ($ api); // call the Sina IP Address Library
$ Arr = json_decode ($ json, true); // parse json
$ Province = $ arr ['Province ']; // Obtain the province
Setcookie ('geodata', $ province, $ time + 600); // Set the cookie and set the expiration time to 10 minutes.
    } 
// Insert visitor information into the data table
Mysql_query ("insert into online (ip, province, addtime) values ('$ IP',' $ province ',' $ time ')");
} Else {// If yes, the user access time is updated.
Mysql_query ("update online set addtime = '$ time' where ip =' $ IP '");

// Delete expired records
$ Outtime = $ time-600;
Mysql_query ("delete from online where addtime <$ outtime ");
// Count the total number of records, that is, the number of online users
List ($ totalOnline) = mysql_fetch_array (mysql_query ("select count (*) from online "));
Echo $ totalOnline; // The total number of output online messages.
Mysql_close ();

 

For details about how to call the Sina IP Address Library, refer to the helloweba.com article to describe how to locate the user's city based on the IP address.

The get_client_ip () function is used to obtain the user's real IP address.

The code is as follows: Copy code

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 number of visitors in each province (region. You can query the database and sort the data by province Group. Note that the final dataset is output in JSON format to facilitate front-end ajax interaction.

The code is as follows: Copy code

Include_once ('connect. Php'); // connect to the database
// Query region Statistics
$ 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); // output in json format

 

JQuery

What needs to be done on the front-end page is to display the total number of visitors during page loading, that is, to use ajax to request online. php. Then, when you move the cursor to the statistics arrow, you can use ajax to request geo. php to obtain the number of online users in each region and show the effect as follows.

The code is as follows: Copy code

$ (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" example .html (str );
});
}, Function (){
$ ("# Onlinelist"). slideUp ("fast ");
});
});

Complete instance

The code is as follows: Copy code

<! Doctype html>
<Html>
<Head>
<Meta charset = "utf-8">
<Title> count the current number of online users in PHP + MySQL + jQuery </title>
<Link rel = "stylesheet" type = "text/css" href = "../css/main.css"/>
<Style type = "text/css">
. Demo {width: 150px; margin: 20px auto; font-size: 14px; position: relative}
# 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; position: absolute; top: 30px; width: 150px}
# 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}
</Style>
<Script type = "text/javascript" src = "../js/jquery. js"> </script>
<Script type = "text/javascript">
$ (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" example .html (str );
});
}, Function (){
$ ("# Onlinelist"). slideUp ("fast ");
});
});
</Script>
</Head>

<Body>


<Div id = "main">
<H2 class = "top_title"> <a href = "blog-206.html" title = "Click to see the tutorial"> PHP + MySQL + jQuery statistics of the current number of online users </a> <Div class = "demo">
<Div id = "total"> online: <span id = "onlinenum"> </span> </div>
<Ul id = "onlinelist">
<Li> </li>
</Ul>
</Div>
<Br/>
 
</Div>

</Body>
</Html>

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.