Web Hosting Talk







View Full Version : User session, keeping logged in. advice needed


acctman
05-19-2009, 04:24 PM
Hi is there a better way to manage user sessions and keep users logged in? The code below is what i'm currently using, and it logs each user into into a table and then every 30mins it checks to see if the user session has expired if yes the entire is removed and they're logged out. But if the user has changed pages within 60secs it updates the session info in the database and resets there time. Can this be optimized in anyway? should i increase te update to prevent timeout for 60sec to like 3-5mins, or do I want to remove the user from the db as soon as possible.


<?php
// Set Session Parameters
session_cache_limiter('must-revalidate');
session_start();
// Declare Headers
header("Expires: Mon, 26 Jul 1997 05:00:00 GMT");
header("Last-Modified: " . gmdate("D, d M Y H:i:s") . " GMT");
header("Cache-Control: no-store, no-cache, must-revalidate");
header("Cache-Control: post-check=0, pre-check=0", false);
header("Pragma: no-cache");
// Check to see if we have a session for this user
$LoadSession=mysql_query("SELECT rmo.* FROM rate_members_online AS rmo LEFT JOIN rate_members AS rm ON rmo.o_id=rm.m_id WHERE rmo.o_session_id='".session_id()."' AND rmo.o_ip='".$ip."'");
$Result=mysql_fetch_assoc($LoadSession);
// Check the Result
if (mysql_num_rows($LoadSession)==0){
// User has no session, create one
mysql_query("INSERT INTO rate_members_online (o_id,o_start,o_last,o_session_id,o_ip) VALUES (".(int)$_SESSION['userid'].", ".time().",".time().",'".session_id()."','".$ip."')");
} else {
// User has a session, perform checks
if ($Result['o_id']!=$_SESSION['userid']){
// User has logged in or out, update session
mysql_query("UPDATE rate_members_online SET o_id='".$_SESSION['userid']."' WHERE o_session_id='".session_id()."' AND o_ip='".$ip."'");
}
if ($Result['o_last']<time()-60){
// User has changed pages within the last 60 seconds, update to prevent timeout
mysql_query("UPDATE rate_members_online SET o_last='".time()."' WHERE o_session_id='".session_id()."' AND o_ip='".$ip."'");
}
}
// Delete session records, only run this every 30 minutes
if (date("i")=="30"){
mysql_query("DELETE FROM rate_members_online WHERE o_last<".(time()-memb_timeout));
}
?>

awatson
05-20-2009, 02:36 PM
Seems ok to me - although your code for emptying old sessions isn't working the way you think I suspect. It'd only get run at half-past the hour (so an hour between runs, not every 30 mins. And it may get run several times if you get a few hits right at half-past.

You'd probably be better off making this part a simple php (or whatever) script that gets run every 30 minutes on a cron job.