Creating a “Who’s Online” script with PHP
(Page 2 out of 2)Where am I?
To include the location of the visitor, the parent page (and not the web bug) must get the location, because if you try to get the location with the web bug, you will always get the location of the web bug (in our case 'whosonline.php'), which is quite useless.
Before writing any code whatsoever, let's first add a new field to our online table:
Next thing we have to add is the code to get the location of the visitor. All we need to do is simply pass the location through a query string, like so:
And the counter now has to store the location as well, which is simply a matter of changing the queries a bit, like so:
$ipaddress = ss($_SERVER['REMOTE_ADDR']);
$lastactive = time();
$intable = $db->query_first ("SELECT onlineid FROM online WHERE ipaddress = '$ipaddress'");
if (!isset($_GET['location'])) { $location = ''; } else { $location = ss($_GET['location']); }
if ($intable == false) {
// Insert new visitor
$db->query ("INSERT INTO online (ipaddress, lastactive, location) VALUES ('$ipaddress', $lastactive, '$location')");
} else {
// Update exisiting visitor
$db->query ("UPDATE online SET lastactive = $lastactive, location = '$location' WHERE ipaddress = '$ipaddress'");
}
You might want to update the display page as well to include the location. To view a live demo, go to page 1, page 2, page 3, and view the display page (this time the display doesn't include the web bug).
This also demonstrates the reason why we used a web bug, instead of simply including a PHP file. Our "Who's Online" script also works with regular HTML pages, or any other page that can include images, but if we had used a PHP include, then only PHP pages could have used the who's online script. A small but very useful advantage indeed!
Automatically getting page titles
At the moment our location display only shows page URL's, but what if we could show the page title of each URL? That would certainly look a lot better, and more professional.
There are several ways of doing this. The easiest way is to include another query string, called title, and let each page pass its own title to the web bug. But you might not want to do this, or you're just too lazy to do it all manually. That's why our web bug will automatically fetch each page, and get its title. For this we're going to use the standard file_get_contents() function and some regular expression magic. Please be note though that opening URL's might be blocked for you, and it's possible that you have to open URL's in a different way (e.g. using the cURL library).
The first thing our web bug has to do is check whether the location passed is a full URL or a relative filename. The below code does what we want:
if (substr($location, 0, strlen('http://')) != 'http://') {
// Yes, relative, create absolute URL
$location = 'http://' . $_SERVER['HTTP_HOST'] . dirname($_SERVER['REQUEST_URI']) . '/' . $location;
}
This code checks if the location starts with http://, and if it doesn't, it creates an absolute URL by adding the host, path and relative filename together.
Next thing we must do is getting the page's HTML, and extracting the title using regular expressions, like so:
if (preg_match ('/
// No title, just exit
return false;
} else {
$title = $match['1'];
}
And that's it. All we have to add now is some code to insert the title into the table, which has a new field as well:
The database code now looks like this:
// Insert new visitor
$db->query ("INSERT INTO online (ipaddress, lastactive, location, title) VALUES ('$ipaddress', $lastactive, '$location', '$title')");
} else {
// Update exisiting visitor
$db->query ("UPDATE online SET lastactive = $lastactive, location = '$location', title = '$title' WHERE ipaddress = '$ipaddress'");
}
And that's all. Go to page 1, page 2, page 3 again, and click here to view a live demo of the above code.
Conclusion
In this tutorial I have shown you how to create your own "Who's Online" script, just like the one that's often found in message boards. The script we've created in this tutorial can easily be extended to support more features, e.g. the ability for visitors to register their name or a page history for each visitor.
One thing I'd like to mention though is that the getting page titles code isn't very efficient at the moment, and if you're going to use it on your website, you should really implement some sort of caching mechanism. At the moment every time a visitor views one of your pages, the page will be hit a second time by the web bug, effectively doubling your server load.
Another thing to take note of is that I used REQUEST_URI quite often in this tutorial, and IIS doesn't support this. If you're using Apache on either Windows or Linux there aren't any problems, but all the code in this tutorial won't work properly because of IIS' lack of support for REQUEST_URI. To fix this you have to write a small function that will get the current URL.
If you need any more help, or have any comments on this tutorial, head over to the PHPit Forums or leave them below.
Click here to download the demo's
December 19th, 2005 at 9:32 pm
[…] Otra cosa interesante fue la de un script para ver “quien esta online”, que siempre es util. […]
February 5th, 2006 at 7:38 am
Your timeout removal is buggy, if you just want to delete users with inactivity of 15 minutes, all entries with (last_activity
February 5th, 2006 at 7:38 am
Sorry, but it was to early and no edit-function is available. I meant 60*TIMEOUT not 15*TIMEOUT ;-)
April 5th, 2006 at 5:55 am
$inactive = time()-(60*60*TIMEOUT);
change to
$inactive = time()-(60*TIMEOUT);
May 22nd, 2006 at 2:38 am
And what about if we want to display the name of my logged-in members instead of their Ip’s?
May 24th, 2006 at 12:39 am
You have to change
echo ‘’ . $visitor[’ipaddress’] . ‘’;
to
echo ‘’ . $visitor[’username’] . ‘’;
this way you see which user is online.
June 22nd, 2006 at 11:20 pm
Nice… I was thinking of eventually adding Forums when I turn my site into a real site and this will be very helpful…
Thanks guys…
June 22nd, 2006 at 11:45 pm
[…] In this tutorial I will show you how to create your own “Who’s Online” script, which is often found on message boards and other community scripts. We will first create a really simple script, and after that add a few more features like the location of each visitor.read more | digg story […]
June 23rd, 2006 at 12:00 am
Not bad. Although a LOT longer than it could be. Try to be simpler. User online -> Add to DB. Cron removes from DB every 5 minutes if added within last 15 minutes. Display countof visitors table. Done.
June 23rd, 2006 at 1:04 am
Way to use to much code. I prefer my approach. (Which is in the website link)
June 23rd, 2006 at 3:45 am
“if (count($online) == 0) {
echo ‘Nobody’;
die();
}”
Sorry to tell you that adding that part of code is stupid. If someone is browsing a page, let it be an user or a bot, then there MUST be at least 1 user. I don’t know if it’s just me, but I hate useless code. Correct me if I am wrong though.
June 23rd, 2006 at 4:03 am
Hey,
Is it possible to incoporate this script into my new website
www.Blogsitesreviews.com
(Made for bloggers by a blogger:)
June 23rd, 2006 at 6:32 am
Using REMOTE_ADDR for user identification is very very very problematic.
Users behind firewalls will all share an IP.
AOL Users change IP more often than drummers change their underwear.
This is probably a Bad Idea.
June 23rd, 2006 at 7:10 am
Don’t use disk access… Change your create table command to use Type=Hash or Memory. This will kill a DB server on useless tasks under load.
June 23rd, 2006 at 9:08 am
Maybe it would make more sense to use a “insert into replace” or “insert on duplicate update”. That way you can drop the first select.
June 23rd, 2006 at 10:18 am
[…] read more | digg story […]
June 23rd, 2006 at 3:27 pm
[…] In this tutorial I will show you how to create your own “Who’s Online” script, which is often found on message boards and other community scripts. We will first create a really simple script, and after that add a few more features like the location of each visitor. But first, let me explain how our “Who’s Online” script is going to work. | […]
June 26th, 2006 at 1:31 pm
[…] Link […]
June 27th, 2006 at 7:19 am
[…] PHPit - Totally PHP » Creating a “Who’s Online” script with PHP (tags: php tutorial whos online) […]
June 27th, 2006 at 1:04 pm
[…] Yet another “online” script. This time, PHPit.net uses a databese and a very small picture. Later they complicate the script and add location besides the IP. Another thing that you might do (is not included in the tutorial) is using Google Maps API and an IP localization software to show a map with the visitors.read more | digg story […]
June 30th, 2006 at 4:27 am
[…] Creating a “Who’s Online” script with PHP In this tutorial I will show you how to create your own “Who’s Online” script, which is often found on message boards and other community scripts. We will first create a really simple script, and after that add a few more features like the location of eac (tags: PHP Forums) […]
July 5th, 2006 at 1:54 am
[…] http://phpit.net/article/creating-whosonline-script-php/read more | digg story […]