Track and display users online time





5
Date Submitted Wed. Oct. 3rd, 2007 8:23 PM
Revision 1 of 1
Helper explode
Tags mysql | PHP | Time | tracking
Comments 1 comments
Well after searching the internet for something similar to this, I didn't come up with anything...so I made my own! This simple script will track your members' time spent on your website. Please feel free to give comments/suggestions/feedback.

<?php
$_SESSION['user_id'] = $userid;
$_SESSION['online_time'] = mktime();
?>
 

<?php
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
}
?>
 

<?php

//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.";
        }else{
                echo "No Logged Time Available";
        }
}

?>
 

<?php
$userid = 5;
showOnlineTime($userid);
?>
 

Comments

Comments $_SESSION
Wed. Apr. 2nd, 2008 3:37 PM    Scripter sehrgut

Voting