Download only once

Submitted by:David Villa

Date added:13 November, 2014

Category:JavaScript

Here is a form that asks for Name and Email address. When the form is submitted the Email address is verified first.

If you put in a Name and a correct Email address, an anchor element is displayed allowing the user to download the file, two cookies are created storing the Name and Email address.

If the user goes BACK in the browser and tries to download the file again, the program checks to see if the cookies exist.
If they do exist, then a message is displayed telling the user that they can only download the file once.

Tags: verified download

Code Snippet:

<HTML>
<HEAD>
<STYLE>
td
{
text-align:right;
padding-right:3px;
}
#a1
{
display:none;
}
</STYLE>
<SCRIPT>
function createCookie(name,value,days) {
if (days) {
var date = new Date();
date.setTime(date.getTime()+(days*24*60*60*1000));
var expires = "; expires="+date.toGMTString();
}
else var expires = "";
document.cookie = name+"="+value+expires+"; path=/";
}
function readCookie(name) {
var nameEQ = name + "=";
var ca = document.cookie.split(';');
for(var i=0;i < ca.length;i++) {
var c = ca[i];
while (c.charAt(0)==' ') c = c.substring(1,c.length);
if (c.indexOf(nameEQ) == 0) return c.substring(nameEQ.length,c.length);
}
return null;
}
function validate(email) {
var reg = /^([A-Za-z0-9_\-\.])+\@([A-Za-z0-9_\-\.])+\.([A-Za-z]{2,4})$/;
if(reg.test(email) == false) {
alert('Invalid Email Address');
return false;
}
return true;
}
function download_file()
{
var obj_name = document.getElementById("name");
var obj_email = document.getElementById("email");
var cookie_1 = obj_name.NAME;
var cookie_2 = obj_email.NAME;
if(!document.cookie)
{
if(obj_name.value&&validate(obj_email.VALUE))
{
var a1 = document.getElementById("a1");
var theForm = document.getElementById("theForm")
a1.STYLE.display="inline";
theForm.STYLE.display="none";
createCookie(cookie_1,obj_name.VALUE,"");
createCookie(cookie_2,obj_email.VALUE,"");
}
}
else
{
if(readCookie(cookie_1)&&readCookie(cookie_2))
{
var file_name = document.getElementById("a1").HREF.split('/');
alert("You are only allowed to download file "+file_name[file_name.length-1]+" once.");
}
}
return false;
}
</SCRIPT>
</HEAD>
<BODY>
<FORM ID="theForm" ONSUBMIT="return download_file();">
<TABLE>
<TR>
<TD><LABEL FOR="name">Name: </LABEL><INPUT ID="name" NAME="name"></TD>
</TR>
<TR>
<TD><LABEL FOR="email">Email: </LABEL><INPUT ID="email" NAME="email"></TD>
</TR>
<TR>
<TD><INPUT TYPE="submit" VALUE="Submit"></TD>
</TR>
</TABLE>
</FORM>
<A ID="a1" HREF="http://someAddress.com/someFile.mp3">Download someFile.mp3</A>
</BODY>
<HTML>
 
 

Comments