Solved

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

Posted on 2008-09-29
8
305 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
 
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
PRTG Network Monitor: Intuitive Network Monitoring

Network Monitoring is essential to ensure that computer systems and network devices are running. Use PRTG to monitor LANs, servers, websites, applications and devices, bandwidth, virtual environments, remote systems, IoT, and many more. PRTG is easy to set up & use.

 
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

Comprehensive Backup Solutions for Microsoft

Acronis protects the complete Microsoft technology stack: Windows Server, Windows PC, laptop and Surface data; Microsoft business applications; Microsoft Hyper-V; Azure VMs; Microsoft Windows Server 2016; Microsoft Exchange 2016 and SQL Server 2016.

Question has a verified solution.

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

These days socially coordinated efforts have turned into a critical requirement for enterprises.
"In order to have an organized way for empathy mapping, we rely on a psychological model and trying to model it in a simple way, so we will split the board to three section for each persona and a scenario and try to see what those personas would Do,…
The viewer will learn how to count occurrences of each item in an array.
The viewer will learn how to create a basic form using some HTML5 and PHP for later processing. Set up your basic HTML file. Open your form tag and set the method and action attributes.: (CODE) Set up your first few inputs one for the name and …

911 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

Need Help in Real-Time?

Connect with top rated Experts

20 Experts available now in Live!

Get 1:1 Help Now