Solved

How to track the length of time a visitor is  on a web page?

Posted on 2008-09-29
8
310 Views
Last Modified: 2013-12-12
Greetings,

I've seen some examples combining JavaScript and PHP that track the length of time a visitor is stays on a website. (http://krahulg.wordpress.com/2007/12/25/how-long-do-your-users-spend-on-a-page/)

This one in particular seems promising, however, I am using a free account to host my site and am not allowed to use fopen.   I am struggling to change the code to insert the variable to a MySQL database.

I would greatly appreciate an example of tracking the length of stay and storing it to a MySQL Database.  (I know how to use PHP to insert to a DB, I do not know how to modify this code to meet my needs.)

Attached is the JS in an HTML file which uses the posted PHP code.
<?php
function logtimemsg($timemsg)
{
//write your own handling code here, store it in a file or store it in a DB, whatever
$logfilename = timelog.txt;
if (is_writable($logfilename))
{
if (!$handle = fopen($logfilename, a))
{
exit;
}
if (fwrite($handle, $timemsg.\r\n) === FALSE)
{
exit;
}
fclose($handle);
}
}
 
logtimemsg($_REQUEST['tmsg']);
?>

Open in new window

monitorme.txt
0
Comment
Question by:UserName01100001
  • 4
  • 3
8 Comments
 
LVL 3

Expert Comment

by:sistemu
ID: 22603918
Hi,

This is an interesting project. I didn't see this made before but I would have an I idea how I would make it.
This is applied for how much time a visitor spends on the entire website, not on a single page. (The last page is not counted.. even though with an Ajax function that would also be manageable.

Put a cookie (with a unique hash) on the users computer and each time a page reloads the new, updated version of the time-period is updated in the database(for that particular hash). Also on each page you could insert a timed ajax function so that after each 1-5 minutes it updates with the server.

Another way, much more imprecise but easier to implement is to measure the time passed between two successive visits of the page. If this interval is greater than 30 minutes the user left the website.
0
 
LVL 5

Expert Comment

by:kumar_jac
ID: 22604315
Hi,
         I can give a clue on that,
If you use google analytics, you can find this thing.
if you want to use chk this url this is free google analytics www.google.com/analytics
 
How they are achiving is,
Every requestest have to distinguesh by some session or IP based
The duration between first & next requests
so you will get the gap based on that you will get average
 
 
Thanks ,
Krishna
 
0
 
LVL 1

Author Comment

by:UserName01100001
ID: 22620965
Thanks for your responses!  

sistemu:

I am very interested in your idea.  I understand how to set a cookie in PHP.  However, I'm still very new to PHP and JavaScript.  Can you provide an example in code?  

Krishna:

I checked out Google Analytics, it does provide an average length of stay by day.  However, I kind of wanted to do it myself to better understand the process.  I am really seeking an example in code.
0
Space-Age Communications Transitions to DevOps

ViaSat, a global provider of satellite and wireless communications, securely connects businesses, governments, and organizations to the Internet. Learn how ViaSat’s Network Solutions Engineer, drove the transition from a traditional network support to a DevOps-centric model.

 
LVL 3

Expert Comment

by:sistemu
ID: 22627584
Hello,
It is not complete, didn't had the time today, but I share what I've got.
The diff column represent the seconds. The AJAX part is not yet implemented... but it should be easy.
But I'll keep on working on it.


<?php 
	@include './../data/conection.php';
	$now = gmdate('Y-m-d H:i:s');	
	if(isset($_COOKIE['timing']))
	{
 
		$id = $_COOKIE['timing'];
			$query="SELECT first, last FROM duration WHERE id='$id' LIMIT 1";
			$query = mysql_query($query);
			$query = mysql_fetch_array($query);
		$first_date = strtotime($query['first']);	
		$last_date = strtotime($query['last']);	
		echo (strtotime($now) - $last_date);
		if(	(strtotime($now) - $last_date) < 60*30)
		{
			echo 'trec';
			$diff = strtotime($now) - $first_date;
			$query="UPDATE duration SET last='$now', diff = '$diff' WHERE id='$id'";
			$query = mysql_query($query);
			$error = mysql_error();
			if ($error) 
				{
				echo " ";
				}
			mysql_close();
		}
		//else create_new_timing
	}
	else
	{//new user
		$query = "SHOW TABLE STATUS WHERE name='duration'";
		$query = mysql_query($query);
		$query = mysql_fetch_array($query);
		$new_id = $query['Auto_increment'];
		$query = "INSERT INTO duration (id, first,last) VALUES ('$new_id', '$now', '$now')";
		$query = mysql_query($query);
		$error = mysql_error();
			if ($error) 
				{
				echo " ";
				}
			mysql_close();
		setcookie("timing", $new_id, 0);
	}
?>
 
 
 
 
========================================
 
 
CREATE TABLE IF NOT EXISTS `duration` (
  `id` int(11) NOT NULL auto_increment,
  `first` datetime NOT NULL,
  `last` datetime NOT NULL,
  `diff` smallint(6) NOT NULL COMMENT 'difference',
  PRIMARY KEY  (`id`)
) ENGINE=MyISAM  DEFAULT CHARSET=latin1 AUTO_INCREMENT=2 ;

Open in new window

0
 
LVL 3

Accepted Solution

by:
sistemu earned 500 total points
ID: 22629391
The final version.. now I can go to sleep :P
If you have any questions, don't be afraid to ask.
active.php.log
index.php.log
0
 
LVL 1

Author Closing Comment

by:UserName01100001
ID: 31502963
sistemu:

Thank you so much for this example!!  It is exactly what I was looking for!  It is a perfect piece of code I can understand and study to better my understanding of both cookies and AJAX.  You are a genius!!

--
Adam
0
 
LVL 3

Expert Comment

by:sistemu
ID: 22641515
Genius is too much, but thanks!
0
 
LVL 1

Author Comment

by:UserName01100001
ID: 22641628
sistemu:

I've been using the rather unfriendly looking UNIX timestamp output with mktime() until your example provided the already formatted output with gmdate().  Thanks for using this priceless little function!

0

Featured Post

Master Your Team's Linux and Cloud Stack!

The average business loses $13.5M per year to ineffective training (per 1,000 employees). Keep ahead of the competition and combine in-person quality with online cost and flexibility by training with Linux Academy.

Question has a verified solution.

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

Suggested Solutions

Color can increase conversions, create feelings of warmth or even incite people to get behind a cause. If you want your website to really impact site visitors, then it is vital to consider the impact color has on them.
When table data gets too large to manage or queries take too long to execute the solution is often to buy bigger hardware or assign more CPUs and memory resources to the machine to solve the problem. However, the best, cheapest and most effective so…
Explain concepts important to validation of email addresses with regular expressions. Applies to most languages/tools that uses regular expressions. Consider email address RFCs: Look at HTML5 form input element (with type=email) regex pattern: T…
Video by: Mark
This lesson goes over how to construct ordered and unordered lists and how to create hyperlinks.

828 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