Friday, November 30, 2012

Number of Users Online script in PHP

Sometime our clients demand for showing how many visitors are online currently on their website. This can be done by many ways. I am going to illustrate two methods of doing this. One is file based and other one is database based. Let us see how to achieve this by both methods one by one.

1) File Based Method:

In this method PHP script writes online visitors information in a text file. That text file is updated after a specific interval of time and script reads that file and show a counter of online visitors where required. Let us see the details of this method step by step,

Step 1) First of all you have to create a .txt file and place it on any folder in your server. In my case I am creating this file on root folder of my website and naming it ip.txt. After updating this file by code, it looks something like this,****1354262381++++****1354262381++++****1354262381++++

Step 2):Then copy and paste the code below where you want to show that counter,

    $pp = strrpos($url,"/");
    $url = substr($url,0,$pp);
    $ura = $_SERVER['SCRIPT_NAME'];
    $host = $_SERVER['SERVER_NAME'];
    $ser = "http://$host";
    $ura= $ser.$ura; 
    $pp1 = strrpos($ura,"/");
    $ura = substr($ura,0,$pp1);
    $url1=explode('/', $url);
    $url1=implode('/', $url1);
    $ura1=explode('/', $ura);
    $ura1=implode('/', $ura1);

    $hm = "$url1"; 
    $hm2 = "$ura1"; 
    include "onlinevisitors.php";

Step 3):  Next step is to create a file named onlinevisitors.php file and place in the folder where you included it in above code. In our case root folder,

$sd  = time();
$count = 1;

$file1 = "ip.txt";
$lines = file($file1);
$line2 = "";

foreach ($lines as $line_num => $line)
 //echo $line."";
 $fp = strpos($line,'****');
 $nam = substr($line,0,$fp);
 $sp = strpos($line,'++++');
 $val = substr($line,$fp+4,$sp-($fp+4));
 $diff = $sd-$val;
 if($diff < 300 && $nam != $rip)
  $count = $count+1;
  $line2 = $line2.$line;
  //echo $line2;

$my = $rip."****".$sd."++++\n";
$open1 = fopen($file1, "w");

echo "<table width=180 height=30 bgcolor=#fdfdfd style=\"border: 1px green solid;\"><tr><td align=left valign=top>";
echo "</td><td align=center>";
echo "<span style=\"font-family: verdana,arial,helvetica; font-size: 11px; font-weight: bold; color: #aaccaa;\">";
echo "Total users online - <font color=red>$count</font></span><br>";
echo "</td></tr></table>";

2) Database Driven Method:

comming soon...

No comments:

Post a Comment

Please feel free to post your comments. If anyone has a good article or good thing to share, just send me that with your name to and if anyone want so receive updates regarding my blog, he can subscribe to my weekly newsletter on "Subscribe to our mailing list" section.