How to count the number of people online in PHP

PHP encapsulates session objects very well. According to HTTP protocol, visitors of each range of websites can generate a unique identifier

echo session_id();

//6ed364143f076d136f404ed93c034201<br />


This is the key to count the number of online users. Only with this session ID can you distinguish the users. Because everyone is different.

Next, how to save the value in the session variable to the database. Here is another function

bool session_set_save_handler ( callable $open , callable $close , callable $read , callable $write , callable$destroy , callable $gc )

//callable, payable, or repayable at any time

// open(string $savePath, string $sessionName) open connection

//close() close the connection

//read(string $sessionId) output data

//write(string $sessionId, string $data) / / write data

//destroy($sessionId) / / delete data

//gc($lifetime) / / garbage collection function


Note that there are several functions with parameters passed in. You just need to indicate that there are passed in functions. PHP will read automatically when executing code

Parameters for in session

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










This completes the main function

Note: you need to use this form to pass the method of an object as a parameter: array (object, "method name")

The next step is to write each function

//open of linked data

function open($path,$sessname) {

  $db = mysql_connect("localhost","root","123456","test");


  mysql_query("SET NAMES UTF8");

  return true;



close the data that can be linked

function close(){

$db = mysql_connect("localhost","root","123456","test");


return true;



The key function is about to start. The read() function is displayed. The read() function is passed in with value, and the session UU ID is passed in

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 there is data in the database, as long as the update time is enough, new data will be written

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


    $sql = "UPDATE session SET data='{$data}', mtime ='{$mtime}'";


    $sql = "INSERT INTO session (sid,data,mtime,ip,card) VALUES('{$sid}','{$data}','".time()."','{$_SERVER['REMOTE_ADDR']}','".self::$card."')";



   return true;



Next is the function that embodies the PHP recycling mechanism. Both 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 = 600;

  $sql = "DELETE FROM session WHERE `mtime`<'".(time()-$max_time)."'";

  mysql_query($sql) or die(mysql_error());

  return true;



OK, all five functions are completed, and then the number of session records read in the middle of the session table. Can accurately count the number of people who are visiting the page.

User records that have not been operated for 10 minutes will be cleared.

The code of how to accurately count the number of people online through php:


$filename='online.txt';//data file

$cookiename='VGOTCN_OnLineCount';//cookie name

$onlinetime=600;//Online effective time in seconds (i.e. 600 equals 10 minutes)



//The PHP file() function reads the entire file into an array. Similar to file ﹣ get ﹣ contents(), the difference is that file() returns the file as an array. Each cell in the array is the corresponding line in the file, including line breaks. false if failed



//Get data that's still valid

foreach($online as $line){



  if(($nowtime - $sesstime)<=$onlinetime){//If it is still within the valid time, the data will continue to be saved, otherwise it will be discarded and no more statistics will be made

    $nowonline[$row[0]]=$sesstime;//Get the online list to the array, the session ID is the key name, and the last communication time is the key value




@Create visitor communication status

Using cookie s to communicate

COOKIE It will fail when the browser is closed, but if the browser is not closed, this COOKIE will remain in effect until the online time set by the program times out


if(isset($_COOKIE[$cookiename])){//If there is COOKIE, i.e. it is not the first visit, the number of people will not be added and the communication time will be updated


}else{//If you don't have COOKIE, it's your first visit

  $vid=0;//Initialize visitor ID

  do{//Give the user a new ID






$nowonline[$uid]=$nowtime;//Update current time status

//Count the number of people online now


//Write data




    foreach($nowonline as $fuid=>$ftime){








echo 'document.write("'.$total_online.'");';


The above is the details of PHP's method of counting the number of people online

More at

How to become an architect from a coder: the 50W annual salary challenge

Tags: PHP Session SQL Database

Posted on Wed, 18 Mar 2020 05:07:54 -0400 by android6011