Jump to content

[SOLVED] Track users online time


Recommended Posts

Hey All,

I need to track the time online of my users on a site. Just like on here where you can see how many days/hours/minutes you have been logged in. I'm a little stuck on how to start. I've done some searches for this sort of thing but I haven't come up with anything decent. Any ideas or places that you can point me to?




Link to comment
Share on other sites

Ok, so I figured it out. Here it is if anyone wants to do something like this.


1. make a "logged_time" column somewhere in your database (I put this in my users table)

2. When they log in do something like this:

$_SESSION['user_id'] = $userid;
$_SESSION['online_time'] = mktime();

3. On the top of each page...or in your header file have this:

if(getUser()){ //<- this checks to see if the user is logged on...you can do this anyway you want
onlineTime(); //<- this alters/saves the online time

4. Here are your main functions


//This function logs the time into the database and makes a new time
function onlineTime(){
//Make DB connection here

$timeout = 5; //this is the timout in minutes

$userid = $_SESSION['user_id'];

$now = time();
$difference = $now - $_SESSION['online_time'];
if($difference <= ($timeout * 60)){
	mysql_query("UPDATE users SET logged_time = logged_time + $difference WHERE userid = $userid");
$_SESSION['online_time'] = mktime();

//This function calculates and outputs the logged time
function showOnlineTime($userid){
//Make DB connection here

$result = mysql_query("SELECT logged_time FROM users WHERE userid = $userid");
if(mysql_num_rows($result) > 0){
	list($total) = mysql_fetch_row($result);
	$days = floor($total / 86400);
	$hours = floor(($total % 86400) / 3600);
	$minutes = floor(($total % 3600) / 60);
	echo "$days days, $hours hours and $minutes minutes.";
	echo "No Logged Time Available";



Simple enough right?

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.

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.