Video Play Counter
The HTML5 video
tag is an easy way to make videos available on your site — without pulling it in from a service that also promotes itself to your site visitors. Videos From Your Website describes how.
This article describes how to log the event when your video's "play" icon is tapped. A count of the number of plays can be published by the video.
Each IP address is counted only once every day. Optionally, you can specify that each IP address is counted only once for all time.
The video at Video — How to Melt Chocolate With an Oven is a live implementation of this code. (The video is about halfway down the page.) The number of views is published immediately above the video, near it's left side.
To see the count increment, tap the "play" icon. Then reload the page. If you repeat those steps, your IP address will not cause another increment.
How it Works
There is a video
tag on your web page with a video that may be played. JavaScript below the video provides counting and count-publishing functionality.
When the page with the video loads, the number of times the video has been played is published. The count is obtained from a log file.
The log file is updated when the "play" icon is tapped. The file contains the date, time, and IP address. There is no log entry adjustment if the person never finishes the video.
The Implementation Parts
There are a number of parts that work together.
-
The web page with the
video
tag contains a place for the video-play count to be published. And it pulls in some JavaScript. -
There is an MP4 video for playing in the
video
tag. -
The JavaScript that is pulled into the page below the
video
tag causes play-icon taps to be recorded; and it also publishes the plays-count number. -
A PHP script records the play-icon taps as the JavaScript gives it the information (via Ajax).
-
A PHP script counts the number of taps and gives the number to the JavaScript (via Ajax).
Okay, let's get this installed and working for you.
Installing Play Count for Your Video
Before the play-tap counting system can work, these must all be ready on the server.
- The count-logging PHP script.
- The counting PHP script.
- The JavaScript.
- The MP4 video.
- The web page with the
video
tag.
When all those are ready on the server, the system is in place.
Installing the Count-Logging PHP Script
The count-logging PHP script can be uploaded into any directory on your server that is accessible to browsers.
Here is the source code. (No customization required.)
<?php /* Log Video Play Version 1.0 April 11, 2020 Will Bontrager Software LLC https://www.willmaster.com/ */ if( empty($_POST['fileLocation']) ) { exit; } $LogLine = array(); $LogLine[] = date('Y-m-d H:i:s'); $LogLine[] = $_POST['ip']; file_put_contents($_SERVER['DOCUMENT_ROOT'].$_POST['fileLocation'],implode("\t",$LogLine)."\n",FILE_APPEND); exit; ?>
Save the PHP script as PlayLogger.php
or other .php
file name that you prefer. The instructions in this article assume PlayLogger.php
is the file name.
Make a note of the URL when PlayLogger.php
is uploaded.
Installing the Counting PHP Script
The counting PHP script can be uploaded into any directory on your server that is accessible to browsers. It may make sense to put both this and the above PHP script into the same directory, but it certainly is not required.
Below is the source code. Following the source code is information about one optional customization.
<?php
/* Tally From Video Log
Version 1.0
April 11, 2020
Will Bontrager Software LLC
https://www.willmaster.com/
*/
$TallyDaily = true; // Set this value to true or false, no quotes.
$IPaddress = array();
foreach( file($_SERVER['DOCUMENT_ROOT'].$_POST['fileLocation']) as $line )
{
$ta = explode("\t",trim($line),2);
if( ! empty($TallyDaily) )
{
$tta = explode(' ',$ta[0]);
$ta[1] = "{$tta[0]} {$ta[1]}";
}
if( isset($IPaddress[$ta[1]]) ) { $IPaddress[$ta[1]]++; }
else { $IPaddress[$ta[1]] = 1; }
}
echo count($IPaddress);
exit;
?>
An Optional Customization —
In the above PHP code, you'll see $TallyDaily = true;
on a line by itself. That will make each IP address be counted once every day that it is logged.
If you prefer each IP address to be counted only once for all time, replace true
with false
(no quotation marks).
Save the PHP script as PlayCounter.php
or other .php
file name that you prefer. The instructions in this article assume PlayCounter.php
is the file name.
Make a note of the URL when PlayCounter.php
is uploaded.
Installing the JavaScript
The JavaScript can be uploaded into any directory on your server that is accessible to browsers. It does not have to be in the same directory as the PHP scripts, but it may make sense to do so unless you have a special directory for external JavaScript files.
Here is the JavaScript source code. It follows with information about the required customizations.
/* JavaScript for Video Play Logger and Counter Version 1.0 April 11, 2020 Will Bontrager Software LLC https://www.willmaster.com/ */ // Customize next five variables. var PlayLogger = "/php/PlayLogger.php"; var PlayCounter = "/php/PlayCounter.php"; var PlayLog = "/php/videolog/PlayLog.txt"; var VideoTagID = "video-for-play-count"; var CountTagID = "play-count"; // End of customization. var count = document.getElementById(VideoTagID); count.addEventListener("playing",CountPlay,false); function CountPlay(e) { if( typeof ip === "undefined" ) { ip = "unavailable"; } var http = new XMLHttpRequest(); if(! http) { return; } var param = new Array(); param.push(param,"fileLocation="+encodeURIComponent(PlayLog)); param.push(param,"ip="+encodeURIComponent(ip)); http.open("POST",PlayLogger,true); http.setRequestHeader("Content-type", "application/x-www-form-urlencoded"); http.send( param.join("&") ); } function PublishPlayCount() { var http = new XMLHttpRequest(); if(! http) { return; } var param = new Array(); param.push(param,"fileLocation="+encodeURIComponent(PlayLog)); http.onreadystatechange = function() { if(http.readyState == 4 && http.status == 200) { document.getElementById(CountTagID).innerHTML = http.responseText; } } http.open("POST",PlayCounter,true); http.setRequestHeader("Content-type", "application/x-www-form-urlencoded"); http.send( param.join("&") ); }
Customizations —
-
var PlayLogger = "
/php/PlayLogger.php
";This is where you specify the location of the
PlayLogger.php
script you installed in a previous step.Replace
/php/PlayLogger.php
with the URL of thePlayLogger.php
file relative to document root. If the absolute URL werehttps://example.com/php/PlayLogger.php
, then/php/PlayLogger.php
would be the value to specify here. -
var PlayCounter = "
/php/PlayCounter.php
";This is where you specify the location of the
PlayCounter.php
script you installed in a previous step.Replace
/php/PlayCounter.php
with the URL of thePlayCounter.php
file relative to document root. See previous step for information about determining a URL relative to document root. -
var PlayLog = "
/php/videolog/PlayLog.txt
";Here is where you specify the location of the log file. It is a plain text file, so a file name extension of
.txt
may make sense.Specify the location relative to document root.
Whatever location you specify for the log file, it must be in a directory where PHP scripts can write to.
-
var VideoTagID = "
video-for-play-count
";video-for-play-count
is the id value of thevideo
tag in the implementation example further below in this article.If you decide to change that id value, change
video-for-play-count
accordingly. -
var CountTagID = "
play-count
";play-count
is the id value of thevideo
tag in the implementation example further below in this article.If you decide to change that id value, change
play-count
accordingly.
Save the JavaScript as PlayCounter.js
or other file name that you prefer. The instructions in this article assume PlayCounter.js
Make a note of the URL when PlayCounter.js
is uploaded.
The MP4 Video
An MP4 video needs to be on your server (or publicly accessible on a server somewhere) for the video
tag to play. You'll need to know the MP4's URL.
And now, the final piece, the video
tag implementation example.
The Web Page With the video
Tag
The web page must be a .php
web page. The reason is that PHP is used to give JavaScript the IP address of the browser using the page.
Here is the source code of video
and script
tags to implement video play counting on the web page. Comments follow.
<div><span id="play-count">#</span> Views</div> <video id="video-for-play-count" style="max-width:100%;" controls> <source src="/myvideo.mp4" type="video/mp4"> </video> <script type="text/javascript"> <?php echo("var ip='{$_SERVER['REMOTE_ADDR']}'"); ?> </script> <script src="/js/PlayCounter.js" type="text/javascript"></script> <script type="text/javascript"> PublishPlayCount(); </script>
Comments —
-
play-count
This is the id value for where the video play count is published. If you change the id value here, change it in the JavaScript accordingly.
(When the web page is loaded, the "#" character following
play-count
is replaced with the actual video play count.) -
video-for-play-count
This is the id value for the
video
tag. If you change the id value here, change it in the JavaScript accordingly. -
/myvideo.mp4
Replace
/myvideo.mp4
with the URL of the MP4 video. -
/js/PlayCounter.js
Replace
/js/PlayCounter.js
with the URL to the external JavaScript file you uploaded earlier.
When the web page is on your server, type its URL into your browser to test it.
Tap play. Then reload the page. The number of views should now be 1.
Counting Plays for Additional Videos
For counting play-icon taps for additional videos, the same installation of PlayLogger.php
and PlayCounter.php
can be used.
But the JavaScript value for the view count log file name needs to be changed (to keep a separate log for each video). Replace /php/videolog/PlayLog.txt
at var PlayLog = "/php/videolog/PlayLog.txt";
with a different log file name.
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