?
Solved

record amount of time a user is logged in

Posted on 2005-05-04
20
Medium Priority
?
293 Views
Last Modified: 2012-08-13
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
0
Comment
Question by:ellandrd
  • 8
  • 6
  • 6
20 Comments
 
LVL 9

Expert Comment

by:AlanJDM
ID: 13930051
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
 
LVL 16

Author Comment

by:ellandrd
ID: 13930119
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
 
LVL 6

Assisted Solution

by:jstretch
jstretch earned 1000 total points
ID: 13930137
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
Concerto Cloud for Software Providers & ISVs

Can Concerto Cloud Services help you focus on evolving your application offerings, while delivering the best cloud experience to your customers? From DevOps to revenue models and customer support, the answer is yes!

Learn how Concerto can help you.

 
LVL 6

Expert Comment

by:jstretch
ID: 13930196
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
 
LVL 16

Author Comment

by:ellandrd
ID: 13930208
>>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
 
LVL 16

Author Comment

by:ellandrd
ID: 13930217
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
 
LVL 6

Expert Comment

by:jstretch
ID: 13930413
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
 
LVL 9

Expert Comment

by:AlanJDM
ID: 13930462
"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
 
LVL 9

Expert Comment

by:AlanJDM
ID: 13930516
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
 
LVL 6

Expert Comment

by:jstretch
ID: 13930592
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
 
LVL 9

Expert Comment

by:AlanJDM
ID: 13930662
"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
 
LVL 6

Expert Comment

by:jstretch
ID: 13930726
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
 
LVL 9

Expert Comment

by:AlanJDM
ID: 13930762
whos ellan?
0
 
LVL 9

Expert Comment

by:AlanJDM
ID: 13930835
"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
 
LVL 16

Author Comment

by:ellandrd
ID: 13933753
$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
 
LVL 9

Expert Comment

by:AlanJDM
ID: 13934333
Did you confirm there are values in prevtime and duration in the database?


Alan
0
 
LVL 16

Author Comment

by:ellandrd
ID: 13934631
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
 
LVL 6

Expert Comment

by:jstretch
ID: 13934636
You need to wrap it in <? ?> tags

0
 
LVL 9

Accepted Solution

by:
AlanJDM earned 1000 total points
ID: 13934705
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

Featured Post

Keep up with what's happening at Experts Exchange!

Sign up to receive Decoded, a new monthly digest with product updates, feature release info, continuing education opportunities, and more.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Nothing in an HTTP request can be trusted, including HTTP headers and form data.  A form token is a tool that can be used to guard against request forgeries (CSRF).  This article shows an improved approach to form tokens, making it more difficult to…
Introduction This article is intended for those who are new to PHP error handling (https://www.experts-exchange.com/articles/11769/And-by-the-way-I-am-New-to-PHP.html).  It addresses one of the most common problems that plague beginning PHP develop…
The viewer will learn how to dynamically set the form action using jQuery.
The viewer will learn how to create and use a small PHP class to apply a watermark to an image. This video shows the viewer the setup for the PHP watermark as well as important coding language. Continue to Part 2 to learn the core code used in creat…
Suggested Courses
Course of the Month15 days, 17 hours left to enroll

850 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question