Jump to content

Archived

This topic is now archived and is closed to further replies.

SieRobin

Auto Logout

Recommended Posts

Is there a way to create some sort of auto logout? I've tried onunload but it really doesn't work too well. All I want is something that displays whether the person is online or not, but if they close the window it still shows them as online, since it didn't run the logout script. Anyone have a good idea or a better way to achieve this?

Share this post


Link to post
Share on other sites
Explain how you are logging in and exactly how you are creating this list of online users? Do you have a custom sessions handler?

Share this post


Link to post
Share on other sites
I'm using sessions, everytime someone is authorized into the site all it really does is put the number 1 into the users database for "online" confirming they're online. Now the problem is, the only way it's going to put 0 in that field confirming that you're logged out, is if someone visits the logout script, if you just close your browser, you're still noted as online.

Could this be accomplished by cookies?

Share this post


Link to post
Share on other sites
instead of using a "1" in your table to show them online, put a timestamp.
each time they click a link in your site, update the timestamp...

then, to show who's online, just query the dbase to show all people on line in the last x number of minutes.

if the person didn't log out, but hasn't clicked a link in the last x minutes, they will not be shown as "online"

Share this post


Link to post
Share on other sites
What you'll have to do is add the users sessionid to the database. Then have a piece of code executes every 15mins which gets sessionid of the user from the database, then you retrieve the users session file and check whether the session is still valid, if it is you dont change the users state, however if isnt then you change the users login state.

There was a post before to a site which showed you how to track users online. I will see if I can dig it up.

Share this post


Link to post
Share on other sites
That'd help, I was actually trying to avoid the timestamp, those get quite annoying after a while.

Share this post


Link to post
Share on other sites
Ha, found it However it doesnt use a database, but implementing a database into should be abe no problem. [url=http://www.llstudios.net/directory/16-1]Here is the tutorial[/url]

Share this post


Link to post
Share on other sites
this topic covers the issue of showing users who are currently online (or have done something in the last x minutes) quite extensively:

[url=http://www.phpfreaks.com/forums/index.php/topic,100488.0.html]http://www.phpfreaks.com/forums/index.php/topic,100488.0.html[/url]

Share this post


Link to post
Share on other sites
I'm quite confused on what they're doing there, I don't work with advanced sessions, is there anyway you could try and explain it to me? I read it all, just was unclear to me. What it seems to be is they want to make a session go into a directory which has a max time, so if the session wasn't ever rendered again it would show them as logged out, thus deleting the file from the directory.

Share this post


Link to post
Share on other sites
I'm trying to avoid timestamps, querying a database for more than 10 people every 5 minutes kind of stresses the site, lol.

Share this post


Link to post
Share on other sites
it's a simple idea:  store a timestamp in the user's session, then update some kind of "last activity" field in a db to the current time.  check on every page whether the user's timestamp is more than x minutes older than the current time - if so, update the session timestamp and the table field again.  and so on.  then when echoing the users online, grab people whose "last activity" field is less than x minutes old.

keep in mind "x" can be any number.  10 minutes, 15 minutes, whatever; this only affects the accuracy of your "users online" count.  updating one field in one row in one table isn't a huge stress on the server, unless you have a ton of users online.  the db is the most efficient and accurate way in my opinion, but if you think it will bog down the server, try a different method.  i'm not sure there is another method that is any more kind to the server.

Share this post


Link to post
Share on other sites
Hmmn, I shall give it a shot, what exactly do I need to do?

Share this post


Link to post
Share on other sites
The best idea is to use the session handlers so when PHP is closing the session it will call your function, when it is garbage collecting it will call your function, when it is opening a session etc. and then you can write custom MySQL code to handle the sessions.
http://ie.php.net/session

Share this post


Link to post
Share on other sites
Isn't there a way just to check if a session has been unset?

Share this post


Link to post
Share on other sites
Ok so how would I go about doing using the session handler?

Share this post


Link to post
Share on other sites
That will be 1 millon pound cheers.

lol.........................

if you dont like it then sorry i tried!

[code]

<?php

# assumed: database connection
# create an online user table


//I'm not a "Grandmaster", (is anyone really?) but the following might help you. First create an online users table by
//running the following function once:

function create_online_users_table()
{
    $query = 'CREATE TABLE online_users (ip VARCHAR(15), updated INT(10), user INT(1), UNIQUE(ip))';
    mysql_query($query) or die ($query.' -- '.mysql_error());
    echo 'online user table created';
}

?>


//Now a function to add users and guests and to delete expired users from the table as well as returning the number of users:
PHP Code:

<?php

# assumed: database connection
# assumed: known users have a cookie: $_COOKIE['user']
# the following will return an array containing the numbers of known and unknown users online

function online_users($period = 300 /* seconds */)
{
    $query = "DELETE FROM `online_users` WHERE `updated` < '".(($now = time()) - $period)."'";
    $result = mysql_query($query) or die ($query.' -- '.mysql_error());
    $query = "INSERT INTO `online_users` (`ip`, `updated`, `user`) ".
             "VALUES ('".$_SERVER['REMOTE_ADDR']."', '".$now."', '".(isset($_COOKIE['user'])?1:0)."')".
             "ON DUPLICATE KEY UPDATE `updated`='$now', `user` = '".(isset($_COOKIE['user'])?1:0)."'";
    mysql_query($query) or die ($query.' -- '.mysql_error());
    $query = "SELECT * FROM `online_users`";
    $result = mysql_query($query) or die ($query.' -- '.mysql_error());
    $return = array('users' => 0, 'guests' => 0);
    if(mysql_num_rows($result) > 0)
    {
        while($row = mysql_fetch_assoc($result))
        {
            if($row['user'] == 1)
            {
                $return['users']++;
            }
            else
            {
                $return['guests']++;
            }
        }
    }
    return $return;     
}

?>
//In use:
//PHP Code:


<?php

# in use
$online = online_users();
$s['users'] = ($online['users'] != 1) ? 's' : NULL;
$s['guests'] = ($online['guests'] != 1) ? 's' : NULL;

#print results
echo <<<END
{$online['users']} user{$s['users']} online!
<br>
{$online['guests']} guest{$s['guests']} online!
END;

?>
[/code]

Share this post


Link to post
Share on other sites
I'm not exactly sure how that works haha, I'm trying to decifer.

Share this post


Link to post
Share on other sites
redarrow: your code has an incredible amount of overhead it looks like.

SieRobin: assuming you have a user table and that the user's ID is stored in the session as user_id, add a column named "last_action" that is a datetime type and run the following function on every page.  $interval is the frequency in minutes with which you want to update the online status.

[code]<?php
function log_action($interval = 5)
{
  // only update the session and table if the "last action" is more than $interval minutes old
  if ($_SESSION['last_action'] <= (time() - $interval*60))
  {
    // update the "last action" to now
    $_SESSION['last_action'] = time();

    // run an update query that looks something like:
    $query = "UPDATE users SET last_action = NOW() WHERE id='{$_SESSION['user_id']}'";
  }
}
?>[/code]

to grab all the users online, simply run a query that looks something like:

[code]SELECT username FROM users WHERE last_action >= DATE_ADD(NOW(), INTERVAL 5 MINUTE)[/code]

you can adjust it to use COUNT(username) instead of username itself to just grab the total number of users online.

Share this post


Link to post
Share on other sites
Question, can I just use a cron job? It'd be easier that way for me, rather than including a file on every page.

Share this post


Link to post
Share on other sites
Doesn't work. If you could help me more that'd be cool lol, sorry.

Share this post


Link to post
Share on other sites
what doesn't work?  what are you storing in the session when the user logs in, and what does your users table look like?

Share this post


Link to post
Share on other sites
I have a column named online where the time is stored, unix correct? Pretty simple really, I'm not sure how to use session handlers therefore that's why I'm asking, so what you want me to do is put a ling of script so that when you login it puts in the unix timestamp into the online column.

Share this post


Link to post
Share on other sites
Also, can I just use a cron job instead, or would that mess it all up?  If I have to include the file on each page that's fine, I'd just like to know.

Share this post


Link to post
Share on other sites

×

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.