How does wordpress display the current number of online users?

Source: Internet
Author: User
Tags json

Today, I went to the blog of qingdou of youlink and found a button on his website that is currently online. It also showed the number of people online, so I couldn't resist the curiosity and moved the mouse over, A drop-down will automatically show the geographical location of online users.


This amazing feature! I immediately asked him for advice and gave me a tutorial. After reading it, I found that the function was implemented in combination with PHP + Mysql + jQuery.

Principle

Use PHP to record the visitor's IP address, record the cookie and expiration time on the client, and use the Sina IP address interface to obtain the geographical location of the visitor (in this example, only the province is recorded), which is written to the mysql table, you can count the total number of visitors within a period of time, or view the regional distribution of visitors.

HTML

Place a div # total that shows the current number of online users and a list that shows the distribution of visitor regions # onlinelist on the page. 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
Use CSS to render 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 ();

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

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.