PHP statistics Current Online User Number example explain _php instance

Source: Internet
Author: User
Tags jquery library

Typically, when a visitor accesses a Web site, the page records the user's cookie information and the user is not on the line when the cookie expires. In this article we use PHP to record the guest IP, and record the cookie and expiration time on the client, at the same time through the Sina IP address interface, get the visitor's geographical location (in this case only record province), written in the MySQL table, you can count the total number of visitors over a period of time, you

Html
We place a div#total on the page displaying the current number of people online and a list of the visitors ' area distribution #onlinelist, by default we place a picture with the loaded animation in the list, and then we use jquery control to show a detailed list when the mouse is sliding.

<div class= "Demo" > 
  <div id= "Total" > Current 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 not let our example is difficult to see, the following code, we use the CSS3, the times are progressing, so we recommend using a modern browser preview 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
We want to prepare a datasheet online to record the guest IP, region and access time. The entire sample statistical process relies on this table, which is structured as follows:

CREATE TABLE IF not EXISTS ' online ' ( 
 ' id ' int (one) not null auto_increment, 
 ' ip ' varchar (= NOT null, 
 ' Provin Ce ' varchar NOT NULL, 
 ' addtime ' int (ten) not null DEFAULT ' 0 ', 
 PRIMARY KEY (' id ') 
) Engine=myisam DEFAULT C Harset=utf8; 

Php
online.php is used to record visitor information, including IP addresses and regions. First detects whether there is a guest IP record in the datasheet, and if so, only update the access time, otherwise, get the user province area and insert the user IP, the province area, into the table. Here, you can determine whether a visitor's cookie record exists, and if not, ask the Sina IP address library to obtain the guest's zone information and set the cookie value and expiration time. Finally, we delete the records that have expired in the table, statistics the total number of records and output, see code comments in detail.

Include_once (' connect.php '); Connection Database $ip = Get_client_ip (); 
Gets the client IP $time = time (); 
Whether the query table has IP as the current guest IP record $query = mysql_query ("Select id from online where ip= ' $ip ')"; if (!mysql_num_rows ($query)) {//If there is no guest IP if ($_cookie[' geodata ']) {//If there is a COOKIE, get the user's zone $province = $_cookie[' Geodat A ']; 
    Regional (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 '];//acquire province Setcookie (' Geodata ', $province, $time +600); Set the cookie, set expiration time to 10 minutes}//Insert guest information into datasheet mysql_query (insert into online (ip,province,addtime) VALUES (' $ip ', ' $pro 
Vince ', ' $time ') "); 
}else{//if present, 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"); Total statistics records, that is, number of online users list ($totalOnline) = Mysql_fetch_array (mysql_query ("Select CounT (*) from online)); 
 echo $totalOnline//Output online total mysql_close ();

function Get_client_ip () is used to get 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[' 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 to the provinces (regions). By querying the database and sorting by province, note that we output the final dataset in JSON format to facilitate front-end Ajax interaction.

Include_once (' connect.php ');//Connection database 
//Query area 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
The front-end page needs to do is to display the total number of visitors when the page is loaded, that is, using AJAX request online.php. Then, when the mouse slides to the statistics arrows, ask geo.php to get the number of online people in the provinces of the region through Ajax, and show the effect in the following way.

$ (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"). html (str); 
    }); 
  },function () { 
    $ ("#onlinelist"). Slideup ("fast"); 
  }); 
 

Finally, the example depends, so don't forget to load the jquery library in the page, which is now in the jquery-1.9.1 version.

is not the content is very wonderful, very rich, is to share to everyone, hope for everyone's learning help.

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.