Software, your way.
burger menu icon
WillMaster

WillMaster > LibraryStatistics and Tracking

FREE! Coding tips, tricks, and treasures.

Possibilities weekly ezine

Get the weekly email website developers read:

 

Your email address

name@example.com
YES! Send Possibilities every week!

Statistics From Videos on Your Website

Statistics can be recorded in conjunction with the HTML5 video tag.

Lots of information is available, enough for a small book. This article provides code for the minimum statistics that many video self-publishers prefer to have available.

  • When the video is started.

  • When the video is viewed to the end.

  • The viewer's IP address.

  • The browser's user-agent information.

  • The URL of the video.

  • The URL of the page with the video tag.

Those will give you a good idea of which web pages people use to view your videos, which videos are viewed and how often, and how many are viewed all the way through to the end.

For aggregate information that you may find valuable when planning future videos, instructions for logging these statistics is also provided in this article:

  • The viewer's country obtained from their IP address.

  • The device type obtained from the browser's user-agent information.

Statistics are logged with your choice of format — CSV or JSON — for easy importing into a spreadsheet. If there is sufficient call for it, I'll write a dashboard for viewing the statistics.

Index

This article is rather extensive. Here is a jump-link index to the various sections.

The 3 Pieces for Minimum Statistics
The video Tag
The JavaScript The PHP Logging Script
For Multiple Videos Per Page
Adding Country to Statistics
Adding Type of Device to Statistics
Testing

The 3 Pieces for Minimum Statistics

Here are the three pieces for minimum statistics.

  1. A video tag so a video can play.

  2. JavaScript to detect when the video is playing and when it has ended, and to send the information to the logging script.

  3. The PHP script that does the logging.

The minimum statistics don't provide the user's country nor the device type they used. Information for those items is later in the article.

The video Tag

The first step is to place the video tag on the web page. Videos From Your Website describes how to implement a video tag.

The web page with the video tag needs to be on a server and accessible with a http or https URL. The reason is that the JavaScript (next section) uses Ajax and Ajax will work only on the internet.

The web page with the video tag also must be a page with a .php file name extension.

Note: For more than one video per web page, each video and its associated JavaScript needs to be published in an iframe tag. More information in the For Multiple Videos Per Page section.

The JavaScript

The JavaScript needs to be customized with the location of the PHP logging script (see The PHP Logging Script, next section). You may wish to install the logging script first so you have its location at hand.

Here is the JavaScript source code. Comments follow.

<script type="text/javascript">
/*
Video Tag Statistics
October 26, 2018
Version 1.1

Will Bontrager Software LLC
https://www.willmaster.com/
Copyright 2018 Will Bontrager Software LLC

This software is provided "AS IS," without 
any warranty of any kind, without even any 
implied warranty such as merchantability 
or fitness for a particular purpose.
Will Bontrager Software LLC grants 
you a royalty free license to use or 
modify this software provided this 
notice appears on all copies. 
*/

/* Customization */
/* At least 1, up to 3 places to customize */

// Place 1:
// The URL of the statistics logger.

var StatisticsLoggerURL = "/VideoStats/Statistics.php";

// Place 2:
// If you have the country-detection PHP script available, 
//   specify it's URL in quotes. Otherwise, specify the 
//   word false without quotes.

var CountryDetectionURL = false;

// Place 3:
// If you have the device-detection PHP script available, 
//   specify it's URL in quotes. Otherwise, specify the 
//   word false without quotes.

var DeviceDetectionURL = false;

/*** End of customization ***/
/****************************/
var Begun = false;
var Device = false;
var Country = false;
var video = document.getElementsByTagName("VIDEO")[0];
var videoSRC = video.getElementsByTagName("SOURCE")[0].src;
var viewerID = String((new Date()).getTime()).substr(-5) + "" + String(parseInt(Math.random()*(99999-10000)+1000));

if( CountryDetectionURL ) { DetectCountry(); }
if( DeviceDetectionURL ) { DetectDevice(); }

function playingHandler(e) { LogTheEvent("playing"); }
function endedHandler(e) { LogTheEvent("ended"); }

video.addEventListener('playing',playingHandler,false);
video.addEventListener('ended',endedHandler,false);

function DetectCountry()
{
    var http =  new XMLHttpRequest();
    if(! http) { return; }
    http.onreadystatechange = function()
    { 
        if(http.readyState == 4)
        {
            if(http.status == 200) { Country = http.responseText; }
        }
    }
    http.open("POST",CountryDetectionURL,true);
    http.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
    http.send( "IP=<?php echo($_SERVER['REMOTE_ADDR']) ?>" );
}

function DetectDevice()
{
    var http =  new XMLHttpRequest();
    if(! http) { return; }
    http.onreadystatechange = function()
    { 
        if(http.readyState == 4)
        {
            if(http.status == 200) { Device = http.responseText; }
        }
    }
    http.open("POST",DeviceDetectionURL,true);
    http.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
    http.send( "UA="+encodeURIComponent("<?php echo($_SERVER['HTTP_USER_AGENT']) ?>") );
}

function LogTheEvent(evnt)
{
    var http =  new XMLHttpRequest();
    if(! http) { return; }
    if( evnt == "playing" )
    {
        if( Begun ) { return; }
        Begun = true;
    }
    else if( evnt == "ended" ) { Begun = false; }
    var param = new Array();
    param.push(param,"Event="+evnt);
    param.push(param,"ID="+viewerID);
    param.push(param,"TimeStamp="+(new Date()).getTime());
    param.push(param,"IP=<?php echo($_SERVER['REMOTE_ADDR']) ?>");
    param.push(param,"VideoURL="+encodeURIComponent(videoSRC));
    param.push(param,"PageURL="+encodeURIComponent(document.URL));
    param.push(param,"Device="+(Device?encodeURIComponent(Device):""));
    param.push(param,"Country="+(Country?encodeURIComponent(Country):""));
    param.push(param,"UserAgent="+encodeURIComponent(navigator.userAgent));
    http.open("POST",StatisticsLoggerURL,true);
    http.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
    http.send( param.join("&") );
}
</script>

Comments —

There is only one place that must be customized. It's the value /VideoStats/Statistics.php on the line beginning with var StatisticsLoggerURL =.

Change /VideoStats/Statistics.php to the URL of the PHP statistics logger. Specify the URL relative to document root. (As an example, the URL relative to document root for the absolute URL http://example.com/stats/script.php is /stats/script.php)

There are two more places that may be customized. Optionally, you may install PHP scripts to obtain the user's country and the user's device type. These may also be added later.

If you have a PHP script to obtain the user's country (see Adding Country to Statistics) —

At the line beginning with var CountryDetectionURL =, change false to the URL of the script. Use the URL relative to document root and publish the URL between quotation marks.

Example:

var CountryDetectionURL = "/vids/UserCountryFromIP.php";

If you have a PHP script to obtain the user's device type (see Adding Type of Device to Statistics) —

At the line beginning with var DeviceDetectionURL =, change false to the URL of the script. Use the URL relative to document root and publish the URL between quotation marks.

Example:

var DeviceDetectionURL = "/vids/DeviceType.php";

The JavaScript can be anywhere on your web page. Near the cancel </body> tag is fine.

External JavaScript —

As an alternative to putting all of the JavaScript on your web page, the JavaScript may be imported from an external URL with a special external file name. It needs the special file name because the JavaScript itself depends on PHP to provide it with some values. See Real Time Update of External JavaScript With PHP for instructions.

The PHP Logging Script

The logging script is a PHP script that logs events to a statistics file associated with the video tag — specifically when the video first starts playing and when the video completes playing.

Here is the source code. It is followed with information about the one customization and the data statistics file.

<?php
/*
Log Video Tag Statistics
October 26, 2018
Version 1.1

Will Bontrager Software LLC
https://www.willmaster.com/
Copyright 2018 Will Bontrager Software LLC

This software is provided "AS IS," without 
any warranty of any kind, without even any 
implied warranty such as merchantability 
or fitness for a particular purpose.
Will Bontrager Software LLC grants 
you a royalty free license to use or 
modify this software provided this 
notice appears on all copies. 
*/

/* One place to customize. */
// If you wish to log with the CSV format, specify a 
//   log file name with .csv file name extension.
// If you wish to log with the JSON format, specify 
//   any other file name extension for the log file.
// The file name may contain a location if the file 
//   is to be written in a directory other than where 
//   this PHP script is installed.

$LogFileName = /stats/VideoLog.csv";

/*** End of customization ***/
/****************************/

if(count($_POST)<9){exit;}
if(strpos($LogFileName,'/')===0) { $LogFileName=(preg_replace('/',preg_quote($_SERVER['DOCUMENT_ROOT'],'/').'/','',$LogFileName)).$LogFileName; }
$_POST['TimeStamp'] = date('r',intval($_POST['TimeStamp']/1000));
if( preg_match('/\.csv$/i',$LogFileName) )
{
    $Keys = array_keys($_POST);
    if( !file_exists($LogFileName) ) { WriteCSVline($Keys,$LogFileName); }
    $ta = array();
    foreach( $Keys as $k ) { $ta[] = $_POST[$k]; }
    WriteCSVline($ta,$LogFileName);
}
else { file_put_contents($LogFileName,json_encode($_POST)."\n",FILE_APPEND); }
exit;

function WriteCSVline($arr,$file)
{
    $count = count($arr);
    for( $i=0; $i<$count; $i++ )
    {
        if( strpos($arr[$i],'"')!==false ) { $arr[$i] = str_replace('"',"\\".'"',$arr[$i]); }
        $arr[$i] = '"' . $arr[$i] . '"';
    }
    file_put_contents($file,implode(',',$arr)."\n",FILE_APPEND);
}
?>

Customization and Statistics File Information —

Customization

The customization is the location of the statistics file. When you specify the location, you are also specifying if you want the statistics file to be formatted CSV or JSON.

See 3 Ways to Specify a File Location for PHP Scripts for ways you can specify the location of the statistics file.

If the file name you specify ends with the .csv file name extension, the statistics file will be formatted CSV. Otherwise, the statistics file will be formatted JSON.

The directory where the statistics file is to be created and updated must be writable by the PHP script. On some servers, this requires a directory permissions change to 777.

If you wish to import the statistics file into your spreadsheet, probably CSV is your best option. However, some spreadsheet software will also import JSON files.

Installation

Save the customized statistics PHP script as Statistics.php (or other .php file name you prefer). Upload Statistics.php to your server and make a note of its URL.

The Statistics File

When the statistics file is created, you'll see a column labeled "ID". That is a unique number assigned to each visitor to the web pages containing your videos. The ID doesn't identify the person; instead, it is a way to identify the playing and ending entries so they can be paired with each other.

The statistics file contains these columns for each entry:

  1. Event

    This will be "playing" or "ended".

  2. ID

    This is a uniqe ID created whenever a web page with a video is loaded. The ID is used to pair the "playing" and "ended" entries when such pairing is desired. Whenever a user starts playing a video and doesn't finish it, there will be no associated "ended" entry for that ID.

  3. TimeStamp

    This is a formatted date and time stamp when the "playing" or "ended" event occurred. If there were pauses or fast forwards during the viewing, the elapsed time between the "playing" and "ended" events will be different than the length of the video.

  4. IP

    The IP address of the visitor.

  5. VideoURL

    The URL of the video that was viewed.

  6. PageURL

    The URL of the web page containing the video.

  7. Device

    The type of device the video was viewed on, if the information is available. Blank otherwise.

  8. Country

    The country the user is from, if the information is available. Blank otherwise.

  9. UserAgent

    The user-agent information provided by the browser.

The statistics data can also be viewed in HTML table format with the software found here:

This is the last of the pieces mentioned in the The 3 Pieces for Minimum Statistics section.

With the 3 installed, you should be good to go. Test it to verify that everything is correct, of course.

For Multiple Videos Per Page

When the same page has more than one video tag, each video and its associated JavaScript needs to be published in an iframe tag.

First, make the individual pages that will be published in the iframe tags. Here is an example:

<!DOCTYPE html>
<html lang="en">
<head>
<meta http-equiv="Content-Type" content="text/html;charset=UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
</head>
<body style="margin:0;">

<video style="max-width:100%;" controls>
    <source src="https://example.com/vids/video.mp4" type="video/mp4">
</video>
<script type='text/javascript' src="VideosJS.php"></script>

</body>
</html>

The above is device-friendly code ready for insertion into an iframe.

style="margin:0;" specifies no margin. This removes any margin the page otherwise would bring into the iframe.

style="max-width:100%;" tells the video tab to expand to 100% of the available width, and no wider. It should then nicely fit the width of the iframe.

https://example.com/vids/video.mp4 needs to be updated with the location of the video file for this video tag.

VideosJS.php needs to be changed. It assumes the JavaScript is in an external file. If not, replace the entire script tag with the JavaScript presented earlier in this article.

To prepare JavaScript to be pulled in from an external file, see External JavaScript.

When the individual files are ready, they can be put into iframe tags.

Here is an example iframe:

<iframe 
   src="VideoA.php" 
   onload="this.style.height=this.contentWindow.document.body.scrollHeight+'px'" 
   style="width:500px; height:360px;">
</iframe>

Replace VideoA.php with the location of the web page containing the video tag to play in this iframe.

Replace width:500px; so it reflects the display width you prefer for the video.

Replace height:360px; so it reflects an approximation of the height of the video. You don't need to be accurate with this. The onload attribute in the iframe tag will adjust the height of the iframe according to the height of the video pulled in.

Make an iframe for each video page and you're good to go.

Adding Country to Statistics

To add the user's country to your video statistics:

  1. Upload the short PHP script below.

  2. Update the JavaScript with the PHP script's URL (see the Comments section at The JavaScript).

Here is the PHP script. Upload it to your server, into the same directory where the customized statistics PHP script Statistics.php is installed, giving it name UserCountryFromIP.php or other file name with a .php file name extension. Then make a note of its URL.

<?php
// Get country from ip-api.com. See http://ip-api.com/docs/ for usage limits.
$data = json_decode( file_get_contents("http://ip-api.com/json/{$_GET[IP]}?fields=country"), true );
echo $data['country'];
exit;
?>

When UserCountryFromIP.php is installed, specify its URL in the customization section of the JavaScript. The JavaScript has instructions.

The UserCountryFromIP.php script is designed to be easily changed if you should want to use a different geolocation provider. The script can be changed without changing anything in the JavaScript related to the video tag.

Adding Type of Device to Statistics

This requires installing two device-type PHP script files.

The first device-type PHP file is obtained from mobiledetect.net. They have a download button marked with the latest version number. The download is a ZIP file.

Here are the steps:

  1. Download the latest version.

  2. Expand/unzip the ZIP file.

  3. In the directory that was created when the ZIP file was expanded, you'll see a file named Mobile_Detect.php.

    Upload Mobile_Detect.php into the same directory where the customized statistics PHP script Statistics.php is installed. (No customization necessary.)

Mobile_Detect.php is frequently updated. Devices are added to the market and browsers are updated, each change introducing new user-agent information. It would be prudent to to replace your installation of Mobile_Detect.php every year or more often with the latest version.

The second device-type PHP file

When the first device-type PHP file has been put on the server, it's time for the second device-type PHP file.

The second device-type PHP file is the short PHP script in the next text box below. No customization required.

Give it name DeviceType.php or other file name with a .php file name extension. Upload DeviceType.php into the same directory on your server where Mobile_Detect.php is at. Make a note of the new script's URL.

<?php
require_once 'Mobile_Detect.php';
$detect = new Mobile_Detect;
echo $detect->isMobile()?($detect->isTablet()?'Tablet':'Phone'):'Computer';
exit;
?>

When DeviceType.php is installed, specify its URL in the customization section of the JavaScript. The JavaScript has instructions.

Testing

To test your installation, use a video that is at least 20 seconds long. You'll want enough time to try various things — pause, reposition the location dot, stop without ending.

Check your log file with each test to verify it is updating information.

When the log file is updating, you're good to go.

Your Videos Published On Your Website lists other articles related to publishing videos with the video tag.

(This article first appeared with an issue of the Possibilities newsletter.)

Will Bontrager

Was this article helpful to you?
(anonymous form)

Support This Website

Some of our support is from people like you who see the value of all that's offered for FREE at this website.

"Yes, let me contribute."

Amount (USD):

Tap to Choose
Contribution
Method

All information in WillMaster Library articles is presented AS-IS.

We only suggest and recommend what we believe is of value. As remuneration for the time and research involved to provide quality links, we generally use affiliate links when we can. Whenever we link to something not our own, you should assume they are affiliate links or that we benefit in some way.

How Can We Help You? balloons
How Can We Help You?
bullet Custom Programming
bullet Ready-Made Software
bullet Technical Support
bullet Possibilities Newsletter
bullet Website "How-To" Info
bullet Useful Information List

© 1998-2001 William and Mari Bontrager
© 2001-2011 Bontrager Connection, LLC
© 2011-2024 Will Bontrager Software LLC