when user leaves

PHP programming forum. Ask questions or help people concerning PHP code. Don't understand a function? Need help implementing a class? Don't understand a class? Here is where to ask. Remember to do your homework!

Moderator: General Moderators

Post Reply
sane993
Forum Newbie
Posts: 22
Joined: Thu Jan 16, 2003 9:44 pm

when user leaves

Post by sane993 »

Hello, Just out of curosity. I see many sites have scripts that say "You have 3 people viewing this page" or "4 member logged in and 2 guest". How can they tell this? I presume it would be written in PHP and I udnerstand that it could be another file that just has some vars and they increase everytime a user loads the page but how can they tell when a user leave? OnUnLoad event handler or sumthing?
User avatar
twigletmac
Her Royal Site Adminness
Posts: 5371
Joined: Tue Apr 23, 2002 2:21 am
Location: Essex, UK

Post by twigletmac »

They tend to (like this forum) show users active in the last x number of minutes. So if a user hasn't done anything in say 5 minutes they get taken off the list of users online.

Mac
elipollak
Forum Newbie
Posts: 22
Joined: Sun Jan 19, 2003 10:23 pm

Post by elipollak »

here's one that I just started to write
Very simple and doesn't yet take into account logged in users
It needs to have a MySQL backend and needs no setup work other than to just run the script in a browser :

Code: Select all

<?php
//========================================================================// 
    $sql_dbName     = "usersonline";

    $db_con = mysql_connect("localhost") OR die ("DB CONNECT Error");

    if (! $db_select = mysql_select_db($sql_dbName)) {
            mysql_create_db($sql_dbName)  OR die ("DB CREATE Error");
            $db_select = mysql_select_db($sql_dbName)  OR die("DB CONNECT Error");  
            mysql_query("create table useronline(timestamp int, ip varchar(16))") OR die("Unable to create table");  
    }
//========================================================================// 
$timeoutseconds   =  300;            //# Timeout value in seconds 
$timestamp = time();  
$timeout = ($timestamp-$timeoutseconds);  
$ip = $_SERVER['REMOTE_ADDR'];

mysql_query("INSERT INTO useronline VALUES('$timestamp', '$ip')")   or die("DB INSERT Error");   
mysql_query("DELETE FROM useronline WHERE timestamp<$timeout")   or die("DB DELETE Error");   

$result = mysql_query("SELECT DISTINCT ip FROM useronline")   or die("DB SELECT Error");   
$users = mysql_num_rows($result);  

mysql_close();  
if ($users==1)  {  echo "$users User online";    }
else 	    {  echo "$users Users online";   }  
?>
sane993
Forum Newbie
Posts: 22
Joined: Thu Jan 16, 2003 9:44 pm

Post by sane993 »

Okay thanks guys. :wink:
Post Reply