Log in

View Full Version : Session Timeout



fg123
08-01-2009, 03:40 AM
Is it possible to detect if a session timed out? I'm making a chat app and i want to detect that if the user's session timed out, the site will update his status to "Offline".

Thx!:confused:

traq
08-02-2009, 12:35 AM
whenever the user sends a chat message, the app needs to send a timestamp with it and save that in a database or text file. When your site serves a page showing everyone's status, it needs to check that timestamp against how long it takes to "timeout" and use that to set the user's status.

fg123
08-04-2009, 06:27 PM
huh?
i don't really get what you are saying. can you please post the code?

traq
08-04-2009, 10:53 PM
the code would depend a lot on how the rest of your app was built. For example, if you're using mySQL, you could add a field called (for example) "lastchat" for each user and then add a function to your chat code to save a timestamp there whenever it sends a chat message. Something like this (not tested):


//I'm still learning MySQL so I can't guarantee this, but I assume you're
// probably using a database with your chat code so I'll give it a go.
// Anyone with better MySQL skills, please chime in!
// I could do it with a flat text file also, but that takes longer and,
// if you *are* using a DB, is unnecessary and will unnecessarily complicate things.

function lastChat(){ // call this function every time a user sends a chat message

$user = $_SESSION['user']; //this assumes that your user is logged in and
// can be identified by some method elsewhere in your code,
// so use whatever already exists here

$time = date(); //unix timestamp

sql = "UPDATE users SET lastchat = $time WHERE username = $user";
//change this user's "lastchat" time to the current time

include "/path/to/DB_connect_script.php"; //include your database connection here

$updateLastChat = mysql_query($sql);

}

Then, when you build your status page, it might include something like this:


function chatStatus(){

include "/path/to/DB_connect_script.php"; //include your database connection here

$sql = "SELECT username, lastchat FROM users";

$result = mysql_query($sql);

while ($row = mysql_fetch_array($result)){
$user = $row['username'];
$lastchat = $row['lastchat'];
$time = date();
$timeSince = $time - $lastchat;
//see if it's been more than 5min since user's last chat message
if ($timeSince > 300){
$status = "$user hasn't said anything lately";
}else{
$status = "$user is chatting it up!";
}
echo "<div id=\"$user\">$status</div>"
}

}

Again, these are untested scripts, just to illustrate my suggestion. They probably don't work "as is." You would have a better shot at writing something that integrates with your existing code.

If anyone has other ideas and/or corrections or improvements to my suggestion, please let us know!

fg123
08-06-2009, 05:51 PM
Thanks, i'll give it a try