Useful Resources for Web Designers and Developers

Advertise

here through BuySellAds

How to create an Email Opt in Box for your Downloads – Part 2

April 3, 2012 on General, Tutorials

So you’re giving away free material from your site. And now you need a way to capture your users’ information. An Opt in box may be the perfect solution for you.

From my previous post, we already have a working box that shows us some static messages, along with a link that takes them to the Feedburner sign up process. This box is automatically shown to all links with a .zip extension. The problem is – people may not want to sign up with Feedburner. So let’s take things a step further.

This tutorial will add a form to our subscribe box, store the email addresses in a database and send the download link to their inbox. This way, you can target only people who want to download. At the same time, we can use this information for future marketing endeavors such as newsletters, updates or what not.

ouroptinbox How to create an Email Opt in Box for your Downloads   Part 2

Note that this will require a bit of PHP and MySQL. Are you ready to begin? Roll up your sleeves and lets start a codin’.

1. Add The Form

Our form will be a simple one. All we need is to grab their email address, and a submit button. Add the code below to our existing opt in box:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
<form method="post" action="process.php" class="emailOptin">    
<table>
    <tr>
	<td colspan="2"><label>Enter your email and check your inbox for the download link: </label></td>
    </tr>
    <tr>
	<td><input type="text" maxlength="100" name="emailaddress" class="emailaddress" /></td>
	<td><input type="submit" class="submitbutton" value="Give it to Me" /></td>
    </tr>
    <tr>
	<td colspan="2"><label class="errormsg"></label></td>
    </tr>
</table>
<input type="hidden" name="linktofile" id="linktofile" value="" />
</form>

Note that our form’s method is “Post”, while our action is “process.php”. This is the file that will handle our processing. Also, we added a hidden field to add our file link. If you recall in part 1 of the tutorial, we are prompting this form to people who want to download our files. This hidden field will contain the value of the link to our file.

Next up is to add some javascript to validate our form. This will prevent the form from being submitted if the email is invalid or empty. Note that this only our client side check – we will validate the submission once again in the server side. Wrap the code below inside script tags:

Client Side Validation:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
$('input.submitbutton').click(function() { 	 
		var hasError = false;
		var emailReg = /^([\w-\.]+@([\w-]+\.)+[\w-]{2,4})?$/; 
		var emailaddressVal = $("input.emailaddress").val();
 
		if(emailaddressVal == '') {
			$('.errormsg').html('Email Cannot be Blank');
			hasError = true;
		}
		else if(!emailReg.test(emailaddressVal)) {
			$('.errormsg').html('Email Has to be a Valid Address');
			hasError = true;
		} 
		if(hasError == true) { 
			return false;
		}
	});

Remember from our first exercise, we have the jQuery library in our pages. So the selector $(‘input.submitbutton’) targets our submit button and it’s click event. The code checks the entry if its empty and if it looks like a good email address. This is achieved using regular expressions. The code returns false if the matches are met – meaning the submit button won’t work.

The Database

Let’s setup the database so we can store the email addresses that we will collect. I use MySql – which is free and comes with XAMPP. I’m using XAMPP to develop locally. You might want to create directly on your hosting – so you can use phpMyAdmin. The process is the same.

Create a database:

create db How to create an Email Opt in Box for your Downloads   Part 2

In your database, create a table named “email” with 2 columns: 1) id – make sure you this is the primary key, and check “auto-increment”, 2) email – this you can set as “VARCHAR” and with 255 length.

create columns How to create an Email Opt in Box for your Downloads   Part 2

You can add extra columns such as name and date – but for the purpose of this tutorial, I’m keeping it to a minimum. Now for the next step – the processing page.

3. The Processing Page

This page will be the one that will store the submitted information to our database. It will also be the one that will send the user the link to the file that they’re downloading.

Create a file – name it “process.php” and store it in the same directory as your opt in form. First we use this brilliant function from Douglas Lovell, which will be our server side validation of the email address from our form.

But why do we need to validate the email again – when we’ve already done so using Javascript in our code above? That is simple – users can disable javascript and submit all sorts of things in our form. They can also inspect our source code and see our form action and method. This allows them to go directly to our processing page with POST values of their own. This is a big no – no. So client and server side validation is necessary. Add the code below to our new page:

Server Side Validation:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
function validEmail($email)
{
   $isValid = true;
   $atIndex = strrpos($email, "@");
   if (is_bool($atIndex) && !$atIndex)
   {
      $isValid = false;
   }
   else
   {
      $domain = substr($email, $atIndex+1);
      $local = substr($email, 0, $atIndex);
      $localLen = strlen($local);
      $domainLen = strlen($domain);
      if ($localLen < 1 || $localLen > 64)
      {
         // local part length exceeded
         $isValid = false;
      }
      else if ($domainLen < 1 || $domainLen > 255)
      {
         // domain part length exceeded
         $isValid = false;
      }
      else if ($local[0] == '.' || $local[$localLen-1] == '.')
      {
         // local part starts or ends with '.'
         $isValid = false;
      }
      else if (preg_match('/\\.\\./', $local))
      {
         // local part has two consecutive dots
         $isValid = false;
      }
      else if (!preg_match('/^[A-Za-z0-9\\-\\.]+$/', $domain))
      {
         // character not valid in domain part
         $isValid = false;
      }
      else if (preg_match('/\\.\\./', $domain))
      {
         // domain part has two consecutive dots
         $isValid = false;
      }
      else if
(!preg_match('/^(\\\\.|[A-Za-z0-9!#%&`_=\\/$\'*+?^{}|~.-])+$/',
                 str_replace("\\\\","",$local)))
      {
         // character not valid in local part unless 
         // local part is quoted
         if (!preg_match('/^"(\\\\"|[^"])+"$/',
             str_replace("\\\\","",$local)))
         {
            $isValid = false;
         }
      }
      if ($isValid && !(checkdnsrr($domain,"MX") || checkdnsrr($domain,"A")))
      {
         // domain not found in DNS
         $isValid = false;
      }
   }
   return $isValid;
}

Then we add the code below to continue our processing code:

1
2
3
4
5
6
if(isset($_POST['emailaddress']) && (!empty($_POST['emailaddress']) && (validEmail($_POST['emailaddress'])))){
    $cleanEmail = mysql_escape_string($_POST['emailaddress'];); 
    mysql_connect("localhost", "root", "") or die();
    mysql_select_db("mydb") or die();
    $sql = 'INSERT INTO users (email) VALUES ("' . $cleanEmail . '")'; 
    mysql_query($sql) or die();

Explanation: First we check if our POST data is set and is not empty and if it is a valid email (we pass our POST variable to the function “validEmail”. If everything looks good – we start our database code. We make sure the email is safe to enter in our database by using mysql_escape_string , and assigning it to a new variable “$cleanEmail”. Then we setup the database connection and credentials, we select the database and prepare our sql statement – appending the $cleanEmail variable. Finally, we execute the query.

Continue with the code below to process the email that goes out to our user:

Sending the Link to the Subscriber:
1
2
3
4
5
6
7
8
9
10
11
12
    $to = $_POST['emailaddress'];
    $link = $_POST['linktofile'];	
    $subject = 'Your Download Link';
    $message = 'You can now download your item by clicking: '  . $link;	
    $headers = 'From:[email protected]' . "\r\n";
    mail($to, $subject, $message, $headers);
    $redirect = "thank-you.php";	
    header("Location: " . $redirect);	
}else{
    $redirect = "problem.php";
    header("Location: " . $redirect);	
}

The above sets up a few more variables : $to is the user’s submitted email address, $link is the hidden field from our form – which contained $subject and $message comprise of our message. The mail function sends our mail and header sends our user to a new page. Notice the else statement – which contains another header function – but to a different page.

4. The Redirect Pages

This part is just a couple of static landing pages to capture the user when a) there’s a problem and b) if their submission is successful:

Create a page called “thank-you.php” and enter the HTML below:

1
<p>Thank you for your submission. Check your inbox for an email from [email protected] </p>

Create another page called “problem.php” and enter the HTML below:

1
<p>There was a problem with your submission. Please check back later. </p>

Conclusion

At this point you should have a working form, a processing page and a database table expecting some data. Test your form and enter a valid email address. If you’re developing locally, chances are you will run into this error: “mail() [function.mail]: Failed to connect to mailserver at “localhost“. Dont’ worry – this is due to your local server is not configured to send emails. Verify that your table has the email address you entered. Important – you also must test the validation code. Put in some bogus characters, and malformed email addresses to do this. It is important that you keep bad data from being injected into your db.

Finally, be aware that this code may not be optimal data wise. Things to keep in mind are ways to prevent spam, duplicate entries and maybe add cookies to prevent “re-popping up” to the same user. Please feel free to share your comments below.

  • http://twitter.com/trezaei Tan Rezaei

    Great tutorial. BUT… A couple of corrections.

    I think, in the database section, you mean to say:

    In your database, create a table named “users” (Not “email”)

    Also, would be helpful for users to know that the php file needs

    … around it.

    Otherwise this was an excellent tool.

    Thank you