How PHP implements and accurately counts the number of online features

Source: Internet
Author: User
Tags flock
in this paper, we describe the method of PHP to realize statistics on-line people. Share to everyone for your reference, as follows:

PHP encapsulates the session object very well, according to the HTTP protocol, each scope of the site's visitors can generate a unique identifier

Echo session_id ();//6ed364143f076d136f404ed93c034201<br/>

This is the key to statistics on the number of people online, only the session_id can distinguish the visitors. Because each person is different.
Next, how to save the value of the session variable inside the database, there will be another function introduced

BOOL Session_set_save_handler (callable $open, callable $close, callable $read, callable $write, Callable$destroy, C Allable $GC)//callable can be withdrawn at any time, the request payable, at any time reimbursable//open (String $savePath, String $sessionName) Open the Connection//close () Close the connection//read ( String $sessionId) pairs out data//write (string $sessionId, String $data)//write Data//destroy ($SESSIONID)//delete data//gc ($lifetime)// Garbage collection functions

Note that there are several functions that have parameters passed in, and you just have to indicate that there is an incoming pass. PHP is automatically read when executing the code

Parameters for the session

The next step is to complete the above five functions and a main function.

Session_set_save_handler (Array ("Session", "open"), Array ("session",   "Close"),   Array ("session", "read "), Array (" session "," write "), Array (" session "   ," destroy "),   Array (" Session "," GC "));

The main function is done.

Note: It is necessary to use this form when passing an object's method as a parameter: Array (object, "method name")

Next is the writing of each function

Link Data openfunction open ($path, $sessname) {  $db = mysql_connect ("localhost", "root", "123456", "Test");  mysql_select_db ("Test", $db);  mysql_query ("SET NAMES UTF8");  return true;}

Closed data can be linked by close

function Close () {$db = mysql_connect ("localhost", "root", "123456", "Test"); Mysql_close ($db); return true;}

The key function to start, the Read function reads (), the main, read () function is a value passed in, the incoming session_id

function Read ($SID) {  $sql = "Select data from session where Sid= ' {$sid} ' and card= '". Self:: $card. "'";  $query = mysql_query ($sql) or Die (Mysql_error ());  $row = Mysql_fetch_array ($query);  $row >0? $row ["Data"]: "";}

The second is the write function, if the database exists in the data, as long as the update time, the new data to write

function Write ($sid, $data) {   $sql = "Select Sid from Session where Sid= ' {$sid} ' and card= '". Self:: $card. "'";   $query = mysql_query ($sql) or Die (Mysql_error ());   $mtime = time ();   $num = mysql_num_rows ($query);   if ($num) {    $sql = "UPDATE session SET data= ' {$data} ', Mtime = ' {$mtime} '";   } else{    $sql = "INSERT into session (Sid,data,mtime,ip,card) VALUES (' {$sid} ', ' {$data} ', '". Time (). "', ' {$_server[' Remote_addr ']} ', '. Self:: $card. "')";   }   mysql_query ($sql);   return true;}

Next is the function that embodies the PHP recovery mechanism, and two functions have parameters passed in.

function Destroy ($SID) {  $sql = "DELETE from session WHERE sid= ' {$sid} '";  mysql_query ($sql) or Die (Mysql_error ());  return true;} Function gc ($max _time) {  $max _time = +;  $sql = "DELETE from session WHERE ' Mtime ' < '". (Time ()-$max _time). "'";  mysql_query ($sql) or Die (Mysql_error ());  return true;}

OK, five functions are finished, and then the session table in the middle of the session to read the number of records. You can accurately count the number of people who are visiting the page.

User records with no operations for 10 minutes will be emptied.

The exact code for how to count the number of people online via PHP:

<?php$filename= ' online.txt ';//Data File $cookiename= ' Vgotcn_onlinecount ';//cookie name $onlinetime=600;//online validity time in seconds ( That is, 600 equals 10 minutes) $online =file ($filename); the//php file () function reads the entire document into an array. Like File_get_contents (), the difference is that file () returns files as an array. Each cell in the array is the corresponding line in the file, including the newline character. If it fails, return false$nowtime=$_server[' Request_time ']; $nowonline =array ();//Get data that is still valid foreach ($online as $line) {$row =  Explode (' | ', $line);  $sesstime =trim ($row [1]); if ($nowtime-$sesstime) <= $onlinetime) {//If it is still within the valid time, the data continues to be saved, otherwise it is discarded and no longer counted $nowonline [$row [0]]= $sesstime;/ Get the online list to an array, the session ID is the key name, the last communication time is the key value}}/*@ create the visitor communication State using cookie communication cookie will expire when the browser is closed, but if you do not close the browser, this cookie will remain in effect until the online time of the program setting expires */if ( Isset ($_cookie[$cookiename])) {//If there is a COOKIE that is not an initial visit, do not add the number of people and update the communication time $uid =$_cookie[$cookiename];}    else{//If no cookie is the initial access $vid =0;//initialize the visitor ID do{//give the user a new ID $vid + +;  $uid = ' U '. $vid;  }while (Array_key_exists ($uid, $nowonline)); Setcookie ($cookiename, $uid);} $nowonline [$uid]= $nowtime;//Update the current time status//statistics are now online $total_online=count ($nowonline);//write Data if ($fp = @fopen ($filename, ' W ')) { if (Flock ($FP, lock_ex)) {rewind ($FP); foreach ($nowonline as $fuid = = $ftime) {$fline = $fuid. ' | '. $ftime. "      \ n ";    @fputs ($fp, $fline);    } flock ($FP, lock_un);  Fclose ($FP); }}echo ' document.write ("'. $total _online. ');
Related Article

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.