record amount of time a user is logged in

i have a webpage site where in the admin control panel, i wnat to display the time that each user is logged in?

at the mo, i can display all users that are currently logged in, but how do i record the amount of time they are logged in? and display that too?

im using sessions and my page is coded in php using a mysql database..

looking for example scripts or clearly stated steps in creating this

Ellandrd
LVL 16
ellandrdAsked:
Who is Participating?
 
AlanJDMCommented:
2 options to automatically refresh a page...

Using HTML - <meta http-equiv="Refresh" content="30; URL=http://www.mysite.com">

Using javascript - <script>setTimeout("location.reload();",30000);</script>

I strongly advise against using either of these. There is nothing that will make me leave a site faster than a page the refreshes without me telling it to.


Alan


0
 
AlanJDMCommented:
It depends on how you are controling the "logging out". How do you hadle a user that doesn't log out properly and simply closes the browser?


Alan
0
 
ellandrdAuthor Commented:
what i have is, when user logs in, i update a table where i store the username and ipaddress. when the click log out, i end all sessions and delete the details from the table...

if the user closed the browser, the session is still alive! maybe i could have some script to end all session belong to user if they close the browser...?

can you help with this too?
0
Cloud Class® Course: C++ 11 Fundamentals

This course will introduce you to C++ 11 and teach you about syntax fundamentals.

 
jstretchCommented:
I'll give it a shot!

You would probably have to setup a new table in the database. This table would track each user and the number of seconds they have been logged in for the current session. Lets call this table: SessionTimer

structure:
id (int) auto_increment, primary key,
userid (int),
prevTime(datetime),
duration(bigint)

-userid links this sessionTimer to a user so you know who it was =P
-prevTime is the last time the duration was updated, updated every time a user clicks a page or something.
-duration is the number of seconds the user is logged in for this session.


Ok so here is my so called process, or maybe its just some random thoughts in my head that dont make sense:
-The user logs in: You would start a new row in the SessionTimer table, setting duration to 0, set the userid to whatever the person's userid is, and set prevTime to the current time: date(m-d-Y h:s). Now get that id that was assigned to that row that was just inserted (select max(id) from SessionTimer) and use this for future pages. You'll probably want to add a variable to the session to track the SessionTimer id, session_register(SessionTimerID) and then access it via $_SESSION['SessionTimerID']

-The user clicks ona link or submits a form: Now once again you have to go into the database and get the row corresponding to this user's session:

select * from SessionTimer where id = $_SessionTimerID

Than subtract the prevTime from the currentTime and add the difference to duration:
$duration += date(m-d-y h:s) - $row[prevTime];
update SessionTimer  SET duration = $duration WHERE id = $_SESSION[SessionTimerID]

Ok i'm going to stop here before this gets ridiculous and I become more confusing.  I just wanted to start off by giving you a good idea of one method for doing this.  I'll reread this and see if I can clarify and show more specific examples. Note: You'd have to get the current date/time in seconds and not use m-d-Y like I did, that just a string format for the date.
0
 
jstretchCommented:
Concerning logout: You could have a script run that searches the SessionTimer table to see if any dates or times are more than 5 minutes old and automatically close that row. Of course if you go that far you can use that to control session time-out and log out the person after 5 minutes, in which case they would start a new SessionTimer entry.
0
 
ellandrdAuthor Commented:
>>jstretch

i have a table called tblOnlineUsers where i store the username and ip address of the user, i could alter that table and add:

prevTime(datetime),
duration(bigint)

to it. then do what you suggested, but you have me confused... am php newbie...

can you be more clearer or give code examples or can somebody else help too?


>>>AlanJDM

and about sessions, aint they always auto destroyed after browser close?
0
 
ellandrdAuthor Commented:
I have read:

"By default, the PHP session cookie expires when the user closes his browser.  The file used to store the session information for a single session is periodically removed automatically if the user exits without terminating the session.  It's probably safe to just not worry about terminating the session."

is this true??
0
 
jstretchCommented:
Closing the browser automatically destroy's the cookie, but you still have to decide what to do with the data in your  database (if your using a database), which you are. If someone clicks logout, you would obviously be able to get an exact time. However, if someone closes their browser, you would not get an exact time, but if they are finished browsing then you wouldn't be off by many seconds.

I assume you are adding a row to tblOnlineUsers whenever someone logs in..this table would be perfect for my suggestion. I'll give you a few code snippets I think would be useful, I would do more but i'm running out of time this evening. I'll assume you already have a mysql_connect etc.. setup.

Note: lets make prevTime a bigint since we'll be working with seconds in the database.

//user logs in, so you want to add a new row
$currentTime = time(); //time() is number of seconds since 1970 Jan 1st 0:00, dont ask me why..
mysql_query("INSERT INTO tblOnlineUsers (username, ip, prevTime, duration) VALUES ($username, $ip, $currentTime, 0);
//now get the primary_key that it gave your new row, so you can acces it from future pages.
$result = mysql_query("SELECT max(id) FROM tblOnlineUsers");
$row = mysql_fetch_assoc($result);
$id = $row['id'];
//add the variable to your session, and set it
session_resgister('SessionTimerID');
$_SESSION['SessionTimerID'] = $id;


//user clicks x link, on the new page you'll want to:
$currentTime = time();
//get prevTime and duration
$result = mysql_query("SELECT * FROM tblOnlineUsers WHERE id = $_SESSION[SessionTimerID]");
$row = mysql_fetch_assoc($result);
$prevTime = $row['prevTime'];
$duration = $row['duration'];

//see how long its been, add it to duration
$difference = $prevTime - $currentTime;
$duration += $difference;

//update the database with the new duration
mysql_query("UPDATE tblOnlineUsers SET duration = $duration WHERE id = $_SESSION[SessionTimerID]");

//now you can display the page!
<html>
<body>
<?  echo "You have been logged in $duration seconds."; //divide by 60 to display minutes of course  ?>

...



0
 
AlanJDMCommented:
"aint they always auto destroyed after browser close"

Yes, at some point. It isn't always right when the browser closes though. That is controled by setting(s) in the ini file. I don't see how killing the session will flag you to update the duration of session though?


Alan
0
 
AlanJDMCommented:
I don't completely agree with having a seperate table to track 'online' users. I usually just add 'loggedin' and 'lastaccessed' to my user table and update those 2 fields when a user logs in and out. In you case you would need to add a duration field to accumalate the tiem logged in. That way I dont have to worry about ID's being in synch and I don't have to do any adding or deleting of records. I also do as jstrech suggested and have a cron'd script checking the last accessed field and automatically logging out users who have lastaccessed time of > now - 5 minutes.


Alan
0
 
jstretchCommented:
If you dont use a seperate table you can't track cool things like: whats the user's average duration?

eg:
$result = mysql_query("SELECT * FROM tblOnlineUsers WHERE userid = $someuserid");
$total_duration = 0;
$numLogins = 0;
while($row = mysql_fetch_assoc($result)) {
   $total_duration += $row['duration'];
   $numLogins++;
}
echo
"User# $someuserid has logged in $numLogins times
for a total of ".$total_duration/60." minutes, an average of".$total_duration/$numLogins/60." minutes per session!";
0
 
AlanJDMCommented:
"whats the user's average duration"

Not something I am interested in, but if I was I would simply add a 'logins' field to the user table to keep a counter. Then, instead of the whole loop you have to use, I simply do this...

"Select (duration / logins) from user where id = ".$userid;



Alan
0
 
jstretchCommented:
Ok, how about adding a date field to track the date they logged in for that particular session? Or a page field to keep track of where they went? etc.... Its up to ellan
0
 
AlanJDMCommented:
whos ellan?
0
 
AlanJDMCommented:
"Ok, how about adding a date field to track the date they logged in for that particular session? Or a page field to keep track of where they went?"

jstrech, we could play the "what if" game all day long. None of these "what if's" are what the original poster asked for. If the request was for "avg duration" or "what page they came from" I would have answered differently. I was merely trying to address what the poster asked for. Your suggestion(s) are perfectly reasonable and would work well, I just prefer to do it differently.


Alan
0
 
ellandrdAuthor Commented:
$currentTime = time();

$prevTime = $row['prevTime'];
$duration = $row['duration'];

$difference = $prevTime - $currentTime;
$duration += $difference;

<?  echo "You have been logged in $duration seconds."; //divide by 60 to display minutes of course  ?>


this code just sits still, doesnt update itself showing amount of time user is logged in?
0
 
AlanJDMCommented:
Did you confirm there are values in prevtime and duration in the database?


Alan
0
 
ellandrdAuthor Commented:
yes these values are in the db and i can print them out to check, but i want something like a timer that shows the amount of time the user is logged in? the code above just shown the seconds and it didnt update as time went on...

something like a clock  beside the users name that shows the length of time the user is been logged in...

hope this helps..

Ellandrd
0
 
jstretchCommented:
You need to wrap it in <? ?> tags

0
Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.

All Courses

From novice to tech pro — start learning today.