PHP calculates the number of online users. PHP collects statistics on the number of online users. Examples of current online instances generally show that when a visitor accesses a website, the page records the cookie information of the user. when the cookie expires, the user is deemed to be offline. PHP statistics on the current number of online users instance explanation, current online instance explanation
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 p # 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.
Currently online:
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.
.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:
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.
Include_once ('connect. php '); // connect to the database $ ip = get_client_ip (); // Obtain the client IP address $ time = time (); // query whether there is a record in the table where ip is the current visitor IP $ 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, then get 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); // $ arr = json_decode ($ json, true ); // parse json $ province = $ arr ['Province ']; // Obtain the province's setcookie ('geodata', $ province, $ time + 600); // Set the cookie, set the expiration time to 10 minutes} // insert the visitor information into the data table mysql_query ("insert into online (ip, province, addtime) values ('$ IP ', '$ province', '$ time') ");} else {// If yes, update the user access time 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; // output the total number of online users mysql_close ();
The get_client_ip () function is used to obtain the user's real IP address.
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.
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.
$(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"); }); });
Finally, the sample dependency, so don't forget to load the jquery library first on the page, which is now in the jquery-1.9.1 version.
Whether the content is wonderful and rich is shared with you. I hope it will be helpful for your learning.
Usually, when a visitor accesses a website, the page records the user's cookie information. when the cookie expires, the user is deemed not online ....