PHP statistics The current number of online users to explain _php instances

Source: Internet
Author: User
Typically, when a visitor visits a website, the page records the user's cookie information, and when the cookie expires, the user is deemed not to be online. In this article we use PHP to record the guest IP, and on the client record the cookie and expiration time, and through the Sina IP address interface, get the visitor's geographical location (this example only records the province), and write to the MySQL table, you can count the total number of visitors over a period of time, but also to view the geographical distribution of visitors.

Html
We put a div#total on the page that shows the current number of people online and a list #onlinelist to show the visitor area distribution, by default we place a picture in the list with the loaded animation, and then we use jquery to control when the mouse slides to show a detailed list.

   Currently Online:   
 
  
  

Css
We use CSS to render the display effect, in order to not make our example difficult to see, the following code, we use CSS3, the Times in progress Ah, so we recommend the use of modern browser preview effect.

Mysql
We want to prepare a data sheet online to record the visitor's IP, region, and access time. The entire sample statistics process relies on this table, which has the following structure:

CREATE TABLE IF not EXISTS ' online ' (  ' id ' int (one) not null auto_increment,  ' IP ' varchar () ' is not null,  ' Provin Ce ' varchar (+) NOT NULL,  ' addtime ' int (ten) not null DEFAULT ' 0 ',  

Php
Online.php is used to record visitor information, including IP addresses and regions. First, the data table is checked for guest IP records, and if so, only the access time is updated, otherwise, the user's province region is obtained and the user IP is inserted into the table. Here, you can determine if there is a visitor's cookie record, if it does not exist, ask the Sina IP address library for the visitor's zone information, and set the cookie value and expiration time. Finally, we delete the records that have expired in the table, count the total number of records and output, see the code comment for details.

Include_once (' connect.php '); Connect database $ip = Get_client_ip (); Gets the client IP $time = time (); The query table has an IP record for the current guest IP $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[' GeoData '];     Area (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 '];//get province Setcookie (' GeoData ', $province, $time +600); Set the cookie, set the expiration time to 10 minutes}//Insert the guest information into the datasheet mysql_query ("INSERT INTO Online" (ip,province,addtime) VALUES (' $ip ', ' $provin Ce ', ' $time ') "); }else{//if present, update the user access time mysql_query ("Update online set addtime= ' $time ' where ip= ' $ip '");}//delete expired Records $outtime = $time-6 00; mysql_query ("Delete from online where addtime< $outtime"); Total number of statistics records, i.e. number of online users list ($totalOnline) = Mysql_fetch_array (mysql_query ("SELECT count (*) from online"); Echo$totalOnline;//Output online total mysql_close ();  

The function get_client_ip () is used to obtain 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";   

Geo.php is used to count the distribution of visitors to the provinces (regions). By querying the database and sorting by province, note that we export the final data set as JSON 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 ']   ;  

Jquery
The front-end page needs to do is to show the total number of visitors when the page loads, that is, using AJAX to request online.php. Then when the mouse slides to the statistical arrows, the AJAX request geo.php to get the number of people in each region province, and the following pull way to show the effect.

$ (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 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 exciting, very rich, is to share to everybody, hope to everybody's study to 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.