Jump to content

Auto Logout


SieRobin

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?
Link to comment
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?
Link to comment
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"
Link to comment
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.
Link to comment
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]
Link to comment
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.
Link to comment
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.
Link to comment
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
Link to comment
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]
Link to comment
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.
Link to comment
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.
Link to comment
Share on other sites

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • Create New...

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.