Measuring online time on website - php

I would like to measure how much time a user spends on my website. It's needed for a community site where you can say: "User X has been spending 1397 minutes here."
After reading some documents about this, I know that there is no perfect way to achieve this. You can't measure the exact time. But I'm looking for an approach which gives a good approximation.
How could you do this? My ideas:
1) Adding 30 seconds to the online time counter on every page view.
2) On every page view, save the current timestamp. On the next view, add the difference between the saved timestamp and the current timestamp to the online time counter.
I use PHP and MySQL if this does matter.
I hope you can help me. Thanks in advance!

This is probably pointless.... what if the user has three tabs open and is "visiting" your site while actually working on the other two tabs? Do you want to count that?

Two factors are working against you -
You can only collect point-in-time statistics (page views), and there's no reasonable way to detect what happened between those points;
Even then, you'd be counting browser window time, not user time; users can easily have multiple tabs open on multiple browser instances simultaneously.
I suspect your best approximation is attributing some average amount of attention time per click and then multiplying. But then you might just as well measure clicks.

Why not just measure what actually can be measured?: referrals, page views, click-throughs, etc.
Collecting and advertising these kinds of numbers is completely in line with the rest of the world of web metrics.
Besides—if someone were to bring up a web page and then, say, go on a two week holiday, how best to account for it?

What you could do is check if a user is active on the page and then send an ajax request to your server every X seconds (would 60 secs be fine?) that a user is active or not on the page.
Then you can use the second method you have mentioned to calculate the time difference between two 'active' timestamps that are not separated by more than one or two intervals. Adding these would give the time spent by the user on your site.

google analytics includes a very powerful event logging/tracking mechanism you can customize and tap into get really good measurements of user behavior - I'd look into that

A very simple solution is to use a hidden iframe that loads a php web page periodically. The loaded web page logs the start time (if it doesn't exist) and the stop time. When the person leaves the page you are left with the time the person first came to the site and the last time they were there. In this case, the timestamp is updated every 3 seconds.
I use files to hold the log information. The filename I use consists of month-day-year ipaddress.htm
Example iframe php code. Put this in yourwebsite/yourAnalyticsiFrameCode.php:
<?php
// get the IP address of the sender
$clientIpAddress=$_SERVER['REMOTE_ADDR'];
$folder = "yourAnalyticsDataFolder";
// Combine the IP address with the current date.
$clientFileRecord=$folder."/".date('d-M-Y')." ".$clientIpAddress;
$startTimeDate = "";
// check to see if the folder to store analytics exists
if (!file_exists($folder))
{
if (!mkdir($folder))
return; // error - just bail
}
if (file_exists($clientFileRecord) )
{
//read the contents of the clientFileRedord
$lines = file($clientFileRecord);
$count = 0;
// Loop through our array, show HTML source as HTML source; and line numbers too.
foreach ($lines as $line_num => $line)
{
echo($line);
if ($count == 0)
$startTimeDate = rtrim( $line );
$count++;
}
}
if ($startTimeDate == "")
$startTimeDate = date('H:i:s d-M-Y');
$endTimeDate = date('H:i:s d-M-Y');
// write the start and stop times back out to the file
$file = fopen($clientFileRecord,"w");
fwrite($file,$startTimeDate."\n".$endTimeDate);
fclose($file);
?>
The javascript to periodically reload the iframe in the main web page.:
<!-- Javascript to reload the analytics code -->
<script>
window.setInterval("reloadIFrame();", 3000);
function reloadIFrame() {
document.getElementById('AnalyticsID').src = document.getElementById('AnalyticsID').src
// document.frames["AnalyticsID"].location.reload();
}
</script>
The iframe in the main web page looks like this:
<iframe id="AnalyticsID" name="AnalyticsID" src="http://yourwebsite/yourAnalyticsiFrameCode.php" width="1"
height="1" frameborder="0" style="visibility:hidden;display:none">
</iframe>
A very simple way to display the time stamp files:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
"http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<title></title>
</head>
<body>
Analytics results
<br>
<?php
$folder = "yourAnalyticsDataFolder";
$files1 = scandir($folder);
// Loop through the files
foreach ($files1 as $fn)
{
echo ($fn."<br>\n");
$lines = file($folder."/".$fn);
foreach ($lines as $line_num => $line)
{
echo(" ".$line."<br>\n");
}
echo ("<br>\n <br>");
}
?>
</body>
</html>
You get a results page like this:
22-Mar-2015 104.37.100.30
18:09:03 22-Mar-2015
19:18:53 22-Mar-2015
22-Mar-2015 142.162.20.133
18:10:06 22-Mar-2015
18:10:21 22-Mar-2015

I think client side JavaScript analytics is the solution for this.
You have the google analitycs, piwik, and there also commercials tools in JS that do exactly that.

Related

Remember MYSQL query results for use in PHP page

I have a PHP page set up to generate a rather large set of data generated from MYSQL queries.
Using this data it will create a certain number of table headers (in html ) dependant on the number of users currently in the system.
foreach($usersFromMYSQL as $row)
{
echo
"
<th>$someUserData
<th>Col Y
<th>Col Z
";
}
It will then also populate the table with a certain of number of rows (in html ) dependant on the number of events occurring in the system
foreach ($eventsFromMYSQL as $row)
{
echo
"
<tr>
";
foreach($usersfromMYSQL as $inner_row)
{
echo
"
<td>$someUserSpecificEventData1
<td>$someUserSpecificEventData2
<td>$someUserSpecificEventData3
";
}
}
This code is heavily simplified, but identical in format, to my website.
My problem is that I am running my website on a Raspberry PI, and the load times for this page are (expectedly) slow due to the number of users and events in the database. Currently each time you access the page all of this data is requested again, and there is (to my knowledge at least) no form of caching or memorisation involved.
The data can possibly change day by day, meaning that if the page where to be cached, I would want it to only remain cached for the remainder of that day, as the next day could possibly have different results.
My question is what solutions exist to prevent this data being reloaded every time the page is visisted, but ensure that it is at least reloaded once a day?
I assume you use MVC system, then it might be done like this :
In your controller, check whether the view page for that day is exists or not.
If not, then get all query and generate all HTML data and then save it as a view file by using unique file name (ex. 2014_01_01.php). After that, load the page.
If exists, direct load the view page for that day.
Please pay attention that once the page is generated for current date, the script should not generate page again.
EDIT 1
If you are using single file,
<?php
$file_name = date('d_m_Y').".php";
if(file_exists($file_name))
{
//load
$page_data = file_get_contents($file_name);
}
else
{
//generate page here
//
$page_data = "....... YOUR HTML PAGE DATA HERE ........ ";
//save it
file_put_contents(date('d_m_Y').".php");
}
//show page to user
echo $page_data;
?>

Auto redirecting to another pages at regular intervals

I want to create an application in PHP.
concept is very simple, I want to just auto load every page randomly at a regular intervals.
For example, if I entered to facebook.com, it would be auto load randomly profile.php, notifications.php, messages.php etc... I am not sure about its practicality. So my question may be stupid, but I need help. I only know meta refresh which is only for refreshing the page.
<meta http-equiv="refresh" content="5; url=http://example.com/">
But I think, using the loop , My concept will work. But I have no idea how loop will work with meta tag.
Looking strange requirement, anyhow, you can use
sleep(5)
function after your page get loads in a recursive way..
you should read this..
The below code will redirect you to the appropriate page. You could check the time stamp, and if it is so much different than the initial page load timestamp, execute the header commmand. You really would be better off using meta in this case.
Header('Location: http://www.google.com');
TrY:
while(1=1){
sleep(5);
//Use one of the following methods to refresh.
echo "<meta http-equiv=\"refresh\" content=\"5; url=/profile.php?pid=".$profile_id."\">";
Header('Location: /profile.php?pid='.$profile_id);
echo "<script>javascript:window.href.replace('/profile.php?pid=".$profile_id."');";
}
also review: Server Sent Events
I finally got the soloution,
<script>
var interval = 5; // in seconds
var pages = [
'http://website.com/link1.php',
'http://website.com/link2.php',
'http://website.com/link3.php'
];
var current_page_index = 0;
setInterval(function() {
loadintoIframe('myframe', pages[current_page_index]);
current_page_index = (current_page_index + 1) % pages.length;
}, interval * 1000); // second setInterval param is milliseconds
</script>

How to evenly split traffic between two pages

Purely hypothetical at this point, no code yet. Trying to figure out the best way to do this. We are company "A" and we have two partners, company "B" and company "C". On a sign up form, we collect data and then pass it on to either partner "B" or parnter "C" - this part is good to go and working fine. I do this with ajax on the front end and a cURL processor on the back end so no one leaves our site and just post the data directly to the partner's form.
Unfortunately due to partner "B" and "C"'s required data the forms we post to are different and we have to have 2 separate html form files, one for each partner. The problem is that we need to do this all from one URL, not a separate one for each partner.
I would guess we would use a 'handler' page that has the specific url - http://www.example.com/parterForm.php
Then in the 'handler' page we would make the switch serve the correct content. I need a way to evenly split who we send data to. I'd like to do the switch on a very granular, MS level for example:
if the time = 0-500 ms - serve Parter B page;
if time = 501-1000ms -serve Partner C page;
all done within the 'handler' page - calling the forms as php includes?
I realize this is not a specific code question and I aplogize, this is something I've never done before and am trying to figure out how to do this. I'm a Creative Director btw who codes, no other resource avail.
thanks.
Hmm, yes, you could do that. That would work reasonably well, in fact. The important thing is to make sure the form goes to the right partner. You could use $_SESSION for that, or check which fields were sent and deduce from that which partner was chosen.
For example:
if( fmod(microtime(),1) < 0.5) include("forms/partner1.php");
else include("forms/partner2.php");
Then when submitted:
$partner1fields = array("name","email","country","dateofbirth");
$partner2fields = array("name","address","postcode","ethnicity");
// the above are examples - they should correspond to the $_POST keys you expect
// now check if they match. Array equality depends on order, so sort first
$postkeys = array_keys($_POST);
sort($postkeys);
sort($partner1fields);
sort($partner2fields);
if( $postkeys == $partner1fields) { /* submit to partner 1 */ }
elseif( $postkeys == $partner2fields) { /* submit to partner 2 */ }
else {
echo "<p>Given keys did not match either partner</p>";
echo "<p>POST keys: ".implode(", ",$postkeys)."</p>";
echo "<p>Partner 1 keys: ".implode(", ",$partner1keys)."</p>";
echo "<p>Partner 2 keys: ".implode(", ",$partner2keys)."</p>";
echo "<p>Please report this error to the site administrator.</p>";
exit;
}
First, by MS I assume you mean the latency between client and server?
Use javascript to either load a tiny image from the server or make an ajax call that gets one char or something and time this. For testing you'll need to do some real pings and adjust your js time to reflect the ping round trip. For example, if the js time to load the image is 500ms but ping time is only 80ms then maybe divide by 6 for the result. This will never be very precise as the client and the server both have processing overhead. Make sure to echo no cache headers or past expire times with the image or ajax response.
Easy, if time <= 500 redirect to form A, if time > 500 redirect to form B or use ajax to load them up.

Pokergame with PHP and Jquery - Browser-Back-Button behaviour

For practicing reasons I programmed a little Texas Holdem Game in PHP with some JQuery Animations. Every action (bet, fold, check, raise, call) is submitted via a HTML form to a PHP script.
Now unfortunately the user is able to just go back to the first betting round after seeing the whole board and the computer's cards and adjusting his betting structure accordingly by using the back-ubtton of the browser.
Is there a practical way for me to prevent this?
Thanks,
Coffeehouse
PS:
A buttonscript is for example this:
if (isset($_POST['call']) AND $_SESSION['bettingcap'] == 1){
$_SESSION['kapitalspieler'] -= $smallbet; // deduct money from player
$_SESSION['pot'] += $smallbet; // add this to the pot
$_SESSION['bettingcap'] = 0; // After call go to next street, so cap is 0
$_SESSION['buttonmodus']=1; // I want to show only certain buttons
$_SESSION['whichstreet']=$_SESSION['whichstreet']+1; // go to next street
$_SESSION['animateagain']='yes'; // show JQuery Animation
}
You need to invalidate the request. That means one request follows after the other.
You do this by storing all requests of that user in the game.
If a new request is send, it can be only added at the end.
You can create the game in memory by initializing it and the pass in all events from all sides until a specific one.
This model does allow you to prevent cheating as well as re-playing a game like in a view mode of previous games.
00 created game ID:#7575
01 player joined seat:1; ID:#12
02 player joined seat:2; ID:#56
03 player joined seat:3; ID:#87
04 deck shuffled order:the cards order here.
05 ...
So you keep these events and if a new request is send by a user you can check if it is okay with the current situation or not.
Perhaps something like this will work.
<SCRIPT type="text/javascript">
window.history.forward();
function noBack() { window.history.forward(); }
</SCRIPT>
</HEAD>
<BODY onload="noBack();"
onpageshow="if (event.persisted) noBack();" onunload="">
From link

Display Ads To % of Users

I have a site that I want to display ads to 10% of my traffic. I am getting on average around 30,000 hits a day and want 10% of those users to see an ad from one of my advertisers.
What's the best way to go about implementing this?
I was thinking about counting the visitors in a database, and then every 10 people that visit 1 user gets an ad. Or is there a better way of going about it?
I'm no good with math, so I'm not sure what's the best approach.
Generate a random number between 1 and 10, and compare it to a fixed number, and your code will run on average 10% of the time:
if (rand(1,10) == 1) {
echo 'ad code';
}
You can make this per-user instead of per-pageview by storing whether that user was 'chosen' in their session.
session_start();
if (isset($_SESSION['show_me_ads']) || rand(1,10) == 1)
$_SESSION['show_me_ads'] = true;
echo 'ad code';
}
I use Google's DFP (Doubleclick for Publishers) to serve ads on my site. It's pretty robust. You have to have an AdSense account, but that's not very hard to obtain, it's just annoying to wait to be approved.
Once you have it set up and your ads loaded in, you can control how many people see your ad by percentage (such as the 10% you were talking about), total pageviews, etc.
Look into it: http://google.com/dfp
If you'd rather not use 3rd party software, I'd think the simplest way would be to randomize it so 1/10 visitors see your ad. The simple way would be:
if (rand(1,10) == 1) {
echo 'YOUR AD CODE HERE';
}
You said you're not good at math, and I understand that, I'm pretty horrible at it too, but basically, every time the page is loaded, it's "rolling" a 10-sided "dice". Every time it "rolls" a 1 (which would be 1 out of 10 times, or 10%), it'll display the ad. Otherwise, it'll be ignored.
The reason this is better than relying on counting the number of users (aside from simplicity) is that it will still roll 1 10% of the time whether you have 30,000 visitors or 3,000,000.
In its simplest form:
if (rand(1,10) == 1) {
echo $ad_content;
}
if(rand ( 1,10) == 1)
display_ads();
You can use
if(mt_rand(1,10)==10){
//show your code;
}
It will show ads to about 10% users
Why would you show ads to a few unlucky ones instead of randomly deciding per page impression (instead of per visitor)?
In php, you can just go ahead and write:
$adPercent = 10;
if (rand(0, 100) < $adPercent) {
echo '<div class="ads">Buy now!</div>';
}
if this was for google ads, then you would need to make the ad insertion optional (using the prob logic above), suggest something along the lines of Google Ads Async (asynchronous)
<script type="text/javascript"><!--
// dynamically Load Ads out-of-band
setTimeout((function ()
{
// placeholder for ads
var eleAds = document.createElement("ads");
// dynamic script element
var eleScript = document.createElement("script");
// remember the implementation of document.write function
w = document.write;
// override and replace with our version
document.write = (function(params)
{
// replace our placeholder with real ads
eleAds.innerHTML = params;
// put the old implementation back in place
document.write=w;
});
// setup the ads script element
eleScript.setAttribute("type", "text/javascript");
eleScript.setAttribute("src", "http://pagead2.googlesyndication.com/pagead/show_ads.js");
// add the two elements, causing the ads script to run
document.body.appendChild(eleAds);
document.body.appendChild(eleScript);
}), 1);
//-->
</script>

Categories