ASPit - Totally ASP JSit - Totally JavaScript
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:

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 ('/(.*?)<<span class="es0">\/</span>title>/is'</span>, <span class="re0">$html</span>, <span class="re0">$match</span><span class="br0">)</span> == <span class="kw2">false</span><span class="br0">)</span> <span class="br0">{</span><br>         <span class="co1">// No title, just exit</span><br>         <span class="kw1">return</span> <span class="kw2">false</span>;<br> <span class="br0">}</span> <span class="kw1">else</span> <span class="br0">{</span><br>         <span class="re0">$title</span> = <span class="re0">$match</span><span class="br0">[</span><span class="st0">'1'</span><span class="br0">]</span>;<br> <span class="br0">}</span></p> </div> <p>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:</p> <div class="sqlcode"> <span class="kw1">ALTER</span> <span class="kw1">TABLE</span> <span class="st0">`online`</span> <span class="kw1">ADD</span> <span class="st0">`title`</span> VARCHAR<span class="br0">(</span> <span class="nu0">255</span> <span class="br0">)</span> <span class="kw1">NOT</span> <span class="kw1">NULL</span> ; </div> <p>The database code now looks like this:</p> <div class="phpcode"> <span class="kw1">if</span> <span class="br0">(</span><span class="re0">$intable</span> == <span class="kw2">false</span><span class="br0">)</span> <span class="br0">{</span><br>         <span class="co1">// Insert new visitor</span><br>         <span class="re0">$db</span>-><span class="me1">query</span> <span class="br0">(</span><span class="st0">"INSERT INTO online (ipaddress, lastactive, location, title) VALUES ('$ipaddress', $lastactive, '$location', '$title')"</span><span class="br0">)</span>;<br> <span class="br0">}</span> <span class="kw1">else</span> <span class="br0">{</span><br>         <span class="co1">// Update exisiting visitor</span><br>         <span class="re0">$db</span>-><span class="me1">query</span> <span class="br0">(</span><span class="st0">"UPDATE online SET lastactive = $lastactive, location = '$location', title = '$title' WHERE ipaddress = '$ipaddress'"</span><span class="br0">)</span>;<br> <span class="br0">}</span> </div> <p>And that's all. Go to <a href="/demo/creating%20a%20whos%20online%20script/page1.html">page 1</a>, <a href="/demo/creating%20a%20whos%20online%20script/page2.html">page 2</a>, <a href="/demo/creating%20a%20whos%20online%20script/page3.html">page 3</a> again, and <a href="/demo/creating%20a%20whos%20online%20script/titledisplay.php">click here to view a live demo</a> of the above code.</p> <h3>Conclusion</h3> <p>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.</p> <p>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.</p> <p>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.</p> <p>If you need any more help, or have any comments on this tutorial, head over to the <a href="/forums/">PHPit Forums</a> or leave them below.</p> <p><a href="/demo/creating%20a%20whos%20online%20script/demos.zip">Click here to download the demo's</a></p> <p style="font-weight:bold;"><a href="/article/creating-whosonline-script-php/1/"></a></p> <div class="alignleft"> « Previous: Introduction & Simple Version </div> <p><br clear="all"> <br></p> <p class="postmetadata alt"><small>This article was posted on Monday, December 12th, 2005 at 12:48 am. You can follow any responses to this article through the <a href="/article/creating-whosonline-script-php/feed/">RSS 2.0</a> feed. You can <a href="#respond">leave a response</a>, or <a href="/article/creating-whosonline-script-php/trackback/" rel="trackback">trackback</a> from your own site.</small></p> </div> </div> <h3 id="comments">22 Responses to “Creating a “Who’s Online” script with PHP”</h3> <ol class="commentlist"> <li class="alt" id="comment-308"> <cite>kbglob - tecnologia para geeks, no para tu mamá » Script en PHP de quien esta conectado</cite> Says:<br> <small class="commentmetadata"><a href="#comment-308" title="">December 19th, 2005 at 9:32 pm</a></small> <p>[…] Otra cosa interesante fue la de un script para ver “quien esta online”, que siempre es util. […]</p> </li> <li class="" id="comment-551"> <cite>Mike Greubel</cite> Says:<br> <small class="commentmetadata"><a href="#comment-551" title="">February 5th, 2006 at 7:38 am</a></small> <p>Your timeout removal is buggy, if you just want to delete users with inactivity of 15 minutes, all entries with (last_activity</p> </li> <li class="alt" id="comment-552"> <cite>Mike Greubel</cite> Says:<br> <small class="commentmetadata"><a href="#comment-552" title="">February 5th, 2006 at 7:38 am</a></small> <p>Sorry, but it was to early and no edit-function is available. I meant 60*TIMEOUT not 15*TIMEOUT ;-)</p> </li> <li class="" id="comment-1024"> <cite>memo</cite> Says:<br> <small class="commentmetadata"><a href="#comment-1024" title="">April 5th, 2006 at 5:55 am</a></small> <p>$inactive = time()-(60*60*TIMEOUT);</p> <p>change to</p> <p>$inactive = time()-(60*TIMEOUT);</p> </li> <li class="alt" id="comment-2396"> <cite>Merden</cite> Says:<br> <small class="commentmetadata"><a href="#comment-2396" title="">May 22nd, 2006 at 2:38 am</a></small> <p>And what about if we want to display the name of my logged-in members instead of their Ip’s?</p> </li> <li class="" id="comment-2526"> <cite>Mike</cite> Says:<br> <small class="commentmetadata"><a href="#comment-2526" title="">May 24th, 2006 at 12:39 am</a></small> <p>You have to change</p> <p>echo ‘’ . $visitor[’ipaddress’] . ‘’;</p> <p>to</p> <p>echo ‘’ . $visitor[’username’] . ‘’;</p> <p>this way you see which user is online.</p> </li> <li class="alt" id="comment-4597"> <cite>Keith L. Dick</cite> Says:<br> <small class="commentmetadata"><a href="#comment-4597" title="">June 22nd, 2006 at 11:20 pm</a></small> <p>Nice… I was thinking of eventually adding Forums when I turn my site into a real site and this will be very helpful…</p> <p>Thanks guys…</p> </li> <li class="" id="comment-4601"> <cite>Remix Resource » Blog Archive » Creating a â��Whoâ��s Onlineâ�� script with PHP</cite> Says:<br> <small class="commentmetadata"><a href="#comment-4601" title="">June 22nd, 2006 at 11:45 pm</a></small> <p>[…] 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 […]</p> </li> <li class="alt" id="comment-4609"> <cite>Johnson</cite> Says:<br> <small class="commentmetadata"><a href="#comment-4609" title="">June 23rd, 2006 at 12:00 am</a></small> <p>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.</p> </li> <li class="" id="comment-4625"> <cite>Eric</cite> Says:<br> <small class="commentmetadata"><a href="#comment-4625" title="">June 23rd, 2006 at 1:04 am</a></small> <p>Way to use to much code. I prefer my approach. (Which is in the website link)</p> </li> <li class="alt" id="comment-4659"> <cite>Joaquin</cite> Says:<br> <small class="commentmetadata"><a href="#comment-4659" title="">June 23rd, 2006 at 3:45 am</a></small> <p>“if (count($online) == 0) {<br> echo ‘Nobody’;<br> die();<br> }”</p> <p>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.</p> </li> <li class="" id="comment-4663"> <cite>Sola</cite> Says:<br> <small class="commentmetadata"><a href="#comment-4663" title="">June 23rd, 2006 at 4:03 am</a></small> <p>Hey,</p> <p>Is it possible to incoporate this script into my new website</p> <p>www.Blogsitesreviews.com</p> <p>(Made for bloggers by a blogger:)</p> </li> <li class="alt" id="comment-4695"> <cite>Richard Lynch</cite> Says:<br> <small class="commentmetadata"><a href="#comment-4695" title="">June 23rd, 2006 at 6:32 am</a></small> <p>Using REMOTE_ADDR for user identification is very very very problematic.</p> <p>Users behind firewalls will all share an IP.</p> <p>AOL Users change IP more often than drummers change their underwear.</p> <p>This is probably a Bad Idea.</p> </li> <li class="" id="comment-4703"> <cite>Russ</cite> Says:<br> <small class="commentmetadata"><a href="#comment-4703" title="">June 23rd, 2006 at 7:10 am</a></small> <p>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.</p> </li> <li class="alt" id="comment-4721"> <cite>Benjamin</cite> Says:<br> <small class="commentmetadata"><a href="#comment-4721" title="">June 23rd, 2006 at 9:08 am</a></small> <p>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.</p> </li> <li class="" id="comment-4729"> <cite>COLD CASE » Blog Archive » Creating a â��Whoâ��s Onlineâ�� script with PHP</cite> Says:<br> <small class="commentmetadata"><a href="#comment-4729" title="">June 23rd, 2006 at 10:18 am</a></small> <p>[…] read more | digg story […]</p> </li> <li class="alt" id="comment-4754"> <cite>Dee’s-Planet! » Creating a “Who’s Online” Script with PHP</cite> Says:<br> <small class="commentmetadata"><a href="#comment-4754" title="">June 23rd, 2006 at 3:27 pm</a></small> <p>[…] 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. | […]</p> </li> <li class="" id="comment-5665"> <cite>the jackol’s den » Creating a “Who’s Online” script with PHP - Mikhail Esteves</cite> Says:<br> <small class="commentmetadata"><a href="#comment-5665" title="">June 26th, 2006 at 1:31 pm</a></small> <p>[…] Link […]</p> </li> <li class="alt" id="comment-5740"> <cite>Smith Data Processing Services » Blog Archive » links for 2006-06-27</cite> Says:<br> <small class="commentmetadata"><a href="#comment-5740" title="">June 27th, 2006 at 7:19 am</a></small> <p>[…] PHPit - Totally PHP » Creating a “Who’s Online” script with PHP (tags: php tutorial whos online) […]</p> </li> <li class="" id="comment-5760"> <cite>Piku’s PHP Blog » Creating a “Who’s Online” script with PHP</cite> Says:<br> <small class="commentmetadata"><a href="#comment-5760" title="">June 27th, 2006 at 1:04 pm</a></small> <p>[…] 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 […]</p> </li> <li class="alt" id="comment-6074"> <cite>A delicious learning experience… » Blog Archive » links for 2006-06-30</cite> Says:<br> <small class="commentmetadata"><a href="#comment-6074" title="">June 30th, 2006 at 4:27 am</a></small> <p>[…] 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) […]</p> </li> <li class="" id="comment-6519"> <cite>Happy Life » Creating a “Who’s Online” script with PHP</cite> Says:<br> <small class="commentmetadata"><a href="#comment-6519" title="">July 5th, 2006 at 1:54 am</a></small> <p>[…] <a href="/article/creating-whosonline-script-php/read" rel="nofollow">http://phpit.net/article/creating-whosonline-script-php/read</a> more | digg story […]</p> </li> </ol> <h3 id="respond">Leave a Reply</h3> <form action="http://phpit.net/wp-comments-post.php" method="post" id="commentform" name="commentform"> <p><input type="text" name="author" id="author" value="" size="22" tabindex="1"> <label for="author"><small>Name (required)</small></label></p> <p><input type="text" name="email" id="email" value="" size="22" tabindex="2"> <label for="email"><small>Mail (will not be published) (required)</small></label></p> <p><input type="text" name="url" id="url" value="" size="22" tabindex="3"> <label for="url"><small>Website</small></label></p> <p> <textarea name="comment" id="comment" cols="100%" rows="10" tabindex="4"></textarea></p> <p><input name="submit" type="submit" id="submit" tabindex="5" value="Submit Comment"> <input type="hidden" name="comment_post_ID" value="77"></p> </form> </div> <div id="rightcontent"> <dl> <dt>About the author</dt> <dd>Dennis Pallett is the main contributor to PHPit. He owns several websites, including ASPit and Chill2Music. He is currently still studying.</dd> </dl> <dl> <dt>Article Index</dt> <dd> <ol style="margin: 0; padding-left:20px;"> <li> <a href="/article/creating-whosonline-script-php/1/">Introduction & Simple Version</a><br> </li> <li> <a href="/article/creating-whosonline-script-php/2/">Location / Title & Conclusion</a><br> </li> </ol> </dd> </dl> <dl> <dt>Bookmark Article</dt> <dd> <div class="addto" onclick="addto(1)"> <img src="/images/addto/blink.gif"><a href="#" onclick="return false;">Add to Blink</a> </div> <div class="addto" onclick="addto(2)"> <img src="/images/addto/del.icio.us.gif"><a href="#" onclick="return false;">Add to Del.icio.us</a> </div> <div class="addto" onclick="addto(3)"> <img src="/images/addto/digg.gif"><a href="#" onclick="return false;">Add to Digg</a> </div> <div class="addto" onclick="addto(4)"> <img src="/images/addto/furl.gif"><a href="#" onclick="return false;">Add to Furl</a> </div> <div class="addto" onclick="addto(5)"> <img src="/images/addto/google.gif"><a href="#" onclick="return false;">Add to Google</a> </div> <div class="addto" onclick="addto(6)"> <img src="/images/addto/simpy.gif"><a href="#" onclick="return false;">Add to Simpy</a> </div> <div class="addto" onclick="addto(7)"> <img src="/images/addto/yahoo.gif"><a href="#" onclick="return false;">Add to Y!MyWeb</a> </div> <div class="addto" onclick="addto(8)"> <img src="/images/addto/spurl.gif"><a href="#" onclick="return false;">Add to Spurl</a> </div> </dd> </dl> <dl> <dt>Download Article</dt> <dd> <a href="?pdf=yes"><img style="float: left; margin-right: 5px;" src="/images/pdf.gif" alt="PDF"></a> <div style="margin-top: 10px;"> Download this article as a PDF file </div> <br clear="all"> </dd> </dl> </div> </div> <div id="footer"> <div> <ul> <li>Advertise</li> <li><a href="/about/">About PHPit</a></li> <li><a href="/contact/">Contact</a></li> <li><a href="/write-for-phpit/">Write for PHPit</a></li> <li><a href="/syndication/">Syndication</a></li> <li id="last"><a href="/privacy/">Privacy Policy</a></li> </ul> </div> <p>Copyright © 2004-2005 The Pallett Group. All Rights Reserved.</p> </div> <script language="JavaScript"> <![CDATA[ var dc_UnitID = 14; var dc_PublisherID = 1592; var dc_AdLinkColor = 'blue'; var dc_adprod='ADL'; ]]> </script> <script language="JavaScript" src="http://kona.kontera.com/javascript/lib/KonaLibInline.js"></script> </body> </html>