2010
05.24

A common task in web development is to track or show a users online time.

Theory

We record and save the time (in seconds) of the users first interaction with our website. On every following click we subtract this information with the current time.

Working example

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
/* tell php to start a new or resume an existing session */
session_start();
 
/* store time of first user interaction */
if(!isset($_SESSION['session.started'])) {
 $_SESSION['session.started'] = time();
}
 
/* calculate time elapsed since first click */
$onlineTime = time() - $_SESSION['session.started'];
 
/* display online time in various formats */
print 'Seconds: '.$onlineTime;
print "<br />\n".'Minutes:'.floor(($onlineTime / 60));
print "<br />\n".'Hours:'.floor(($onlineTime / 60 / 60));
print "<br />\n".'Days:'.floor(($onlineTime / 60 / 60 / 24));

  PHP - Track user online time (651 bytes, 307 hits)

Enjoy!

No Comment.

Add Your Comment
*