« AJAX File Uploader, The AJAX Progress Bar | Main | Ajax training workshop »

AJAX Real Time Online Visitors Tutorial

I tryed in the previous tutorial to make something easy to understand, and we'll try to see in this tutorial how we can play with the previous code to make an AJAX Real Time Online Visitors. The idea of the script is simple, the javascript request a remote script to get the number of online visitors and update it every minutes or two. So while visiting a page you can see the number of visitors changing in real time.

AJAX online visitors

The PHP Script


There is many techniques to track online visitors with PHP, in this example I used the most simple one. The script check the sessions online and then consider the recent ones in an interval of about 3 minutes. This gives more realistic information, because visitors idle for a long period are considered not online, and in the same time we don't have to create complex script and store informations in database ... etc.


// idle time in minutes
define("MAX_IDLE_TIME", 3); 

function who(){

$path = session_save_path();
if (trim($path)=="") {
return FALSE;
}
$d = dir( $path); $i = 0;
while (false !== ($entry = $d->read())) {

if ($entry!="." and $entry!="..") {
if (time()- filemtime($path."/$entry") < MAX_IDLE_TIME * 60 ) {
$i++;
}
}
}
$d->close();

return $i;
}

AJAX code

The javascript didn't change a lot, we just have less code. What we need in this case is just getting the data and display it, nothing to parse or to change. Timer have been set to update the counter every minute.

var RequestObject = false; // XMLHttpRequest Object
var Backend = 'http://www.phpmagazine.net/demo/ajaxonline/check.php'; // Counter url
window.setInterval("update_timer()", 60000); // update the data every 1 min



The main AJAXRequest and the ReqChange function in our case will be

/*
* Main AJAX online Visitor counter request
*/
function AJAXRequest() {

// change the message to Checking online ...
document.getElementById("online").innerHTML = "Checking online ...";

// Prepare the request
RequestObject.open("GET", Backend , true);
// Set the onreadystatechange function
RequestObject.onreadystatechange = ReqChange;
// Send
RequestObject.send(null);
}
/*
* onreadystatechange function
*/
function ReqChange() {

// If data received correctly
if (RequestObject.readyState==4) {

// if data is valid
if (RequestObject.responseText.indexOf('invalid') == -1)
{
// getting the response
var msgs = RequestObject.responseText.split('|');

// Tell the reader the everything is done
document.getElementById("online").innerHTML = msgs[0]+" visitors online";

}
else {
// Tell the reader that there was error requesting data
document.getElementById("online").innerHTML = "Error Requesting data";
}
}

}


In addition to this script I have used a div "online" that you can put anywhere in your page



AJAX online visitors



This is another way to use AJAX with PHP to retrieve information about online visitors, you can test the AJAX Online visitor script online, the PHP Script you can get it from here.

Bookmark this article at these sites
Comments
1

Great script! It's working perfect on a share web site, but not on a vps server, I receive the error:
Parse error: parse error, unexpected '&' in /home/www/mydomain/html/onlineusers/check.php on line 37

2

There is nothing that make it not working on vps or shared hosting. On vps you have the ability to compile PHP, apache ... and so on, thing that shared hosting account can't do.

If you can give more details about your config, maybe I can help you more.

3

I see you are calling three functions to make a request, why don't you use only one:
SendRequest("GET", Backend , true, reqChange, onError);
and you define your three functions inside RequestObject

also same with reqChange()
you don't need to check readyState every time you call the function, you can encapsulate it in RequestObject,,, when a result is really returned you just process the response text, if not an onError function is called.

4

Not very accurate for shared hosting...since many shared hosting servers will just use /tmp as the session path. Thus everyone on the server using session variables will get tallied into your total, not to mention any other files saved there in the last MAX_IDLE_TIME mins :-)

5

I have the function 'ReqChange()' but I really want to add a variable to it. (to make it 'ReqChange(variable)' and then RSSRequestObject.onreadystatechange = ReqChange(example);

However, when I do this the program breaks down.

Any ideas how I get around this?

6

I used ajax online script but it only shows "visitors online" with no number even though I have 20 to 30 people on at any time.

Any ideas?

I just copies your script verbatem except changed the link to check.php of course.

7

Merle, the folder you have your PHP session data in does not have the proper read permissions. That's why it hangs. Try accessing the check.php directly to confirm.

This script basically reads all of the PHP session data. I would think that chmoding that dir and opening access to that data would create a potential security nightmare. I mean, it's supposed to be locked down for a reason isn't it?

It's a great theory, but not so great in practice. I would like to see what the other ways of doing this are?

8

Perfect Homepage:

RSSRequestObject.onreadystatechange = function(){ReqChange(example);};

Post a comment





(Email will remain hidden)





Please enter the security code you see here




Related entries
Email to a friend
Email this article to:


Your email address:


Message (optional):