ASPit - Totally ASP JSit - Totally JavaScript

PHPit - Totally PHP

Search PHPit

Use this textbox to search for articles on PHPit. Seperate keywords with a space.

Advertisements

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:

ALTER TABLE `online` ADD `location` VARCHAR( 255 ) NOT NULL ;

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:

<img src="locationcounter.php?location=locationdisplay.php" alt="" />

And the counter now has to store the location as well, which is simply a matter of changing the queries a bit, like so:

// Check if visitor is already in the table
$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:

// Relative or not?
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:

$html = file_get_contents($location);

if (preg_match ('/<title>(.*?)<\/title>/is', $html, $match) == false) {
        // 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:

ALTER TABLE `online` ADD `title` VARCHAR( 255 ) NOT NULL ;

The database code now looks like this:

if ($intable == false) {
        // 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



22 Responses to “Creating a “Who’s Online” script with PHP”

  1. kbglob - tecnologia para geeks, no para tu mamá » Script en PHP de quien esta conectado Says:

    […] Otra cosa interesante fue la de un script para ver “quien esta online”, que siempre es util. […]

  2. Mike Greubel Says:

    Your timeout removal is buggy, if you just want to delete users with inactivity of 15 minutes, all entries with (last_activity

  3. Mike Greubel Says:

    Sorry, but it was to early and no edit-function is available. I meant 60*TIMEOUT not 15*TIMEOUT ;-)

  4. memo Says:

    $inactive = time()-(60*60*TIMEOUT);

    change to

    $inactive = time()-(60*TIMEOUT);

  5. Merden Says:

    And what about if we want to display the name of my logged-in members instead of their Ip’s?

  6. Mike Says:

    You have to change

    echo ‘’ . $visitor[’ipaddress’] . ‘’;

    to

    echo ‘’ . $visitor[’username’] . ‘’;

    this way you see which user is online.

  7. Keith L. Dick Says:

    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…

  8. Remix Resource » Blog Archive » Creating a â��Whoâ��s Onlineâ�� script with PHP Says:

    […] 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 […]

  9. Johnson Says:

    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.

  10. Eric Says:

    Way to use to much code. I prefer my approach. (Which is in the website link)

  11. Joaquin Says:

    “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.

  12. Sola Says:

    Hey,

    Is it possible to incoporate this script into my new website

    www.Blogsitesreviews.com

    (Made for bloggers by a blogger:)

  13. Richard Lynch Says:

    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.

  14. Russ Says:

    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.

  15. Benjamin Says:

    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.

  16. COLD CASE » Blog Archive » Creating a â��Whoâ��s Onlineâ�� script with PHP Says:

    […] read more | digg story […]

  17. Dee’s-Planet! » Creating a “Who’s Online” Script with PHP Says:

    […] 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. | […]

  18. the jackol’s den » Creating a “Who’s Online” script with PHP - Mikhail Esteves Says:

    […] Link […]

  19. Smith Data Processing Services » Blog Archive » links for 2006-06-27 Says:

    […] PHPit - Totally PHP » Creating a “Who’s Online” script with PHP (tags: php tutorial whos online) […]

  20. Piku’s PHP Blog » Creating a “Who’s Online” script with PHP Says:

    […] 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 […]

  21. A delicious learning experience… » Blog Archive » links for 2006-06-30 Says:

    […] 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) […]

  22. Happy Life » Creating a “Who’s Online” script with PHP Says:

    […] http://www.phpit.net/article/creating-whosonline-script-php/read more | digg story […]

Leave a Reply

About the author
Dennis Pallett is the main contributor to PHPit. He owns several websites, including ASPit and Chill2Music. He is currently still studying.
Article Index
  1. Introduction & Simple Version

  2. Location / Title & Conclusion

Bookmark Article
Download Article
PDF
Download this article as a PDF file