We have a new website (We've moved)! So go check out Phosphorus.co

How to Make an Email Based Subscription Service

Posted in PHP, Tutorials
preview2

Email is simply a way to send mail electronically to people in text and image form, with attachments if required. Email has been called the internet’s “killer app” and is generally considered one of the first things people think of when they think of the internet.

That’s why when you want to update your users on what’s happening on your website, we use a mailing list or a subscription service where the user enters their email address, validates it, and recieves updates from you. In this tutorial we’ll cover how exactly to do that, and hopefully you’ll learn a thing or two about PHP and MySQL along the way.





demodownload

In this little tutorial we’ll be going over how to make a nice email subscription type service. This can be useful if you want to set up your own DIY mailing list, and hopefully it’ll give you a better grasp of PHP and MySQL.

CSS, you say?

Lets start by making the script that allows users to subscribe and what not. First thing I did was to set up a little CSS script, to make everything look prettier. This is all rather straight forward, so I’m not going to explain it.


body {
background: #23292e;
margin: 20px;
font-family: Helvetica, Arial, sans-serif;
}

.message {
background: #e8ed90;
border: 1px solid #a9ae54;
padding: 15px;
width: 500px;
font-weight: bold;
font-size: 14px;
color: #7c7834;
}

.form {
font-weight: bold;
padding: 15px;
color: #cbd0d3;
}

input {
padding: 5px;
font-family: Helvetica, Arial, sans-serif;
}

Just stick it in a file called style.css and include it in your html document:

<link rel="stylesheet" href="style.css" type="text/css" />

Now that that’s out of the way, let’s get down to some hard coding and databasing.

MySQL

We’re going to required a database to store all these emails and what not in, and MySQL is the database client to do it!  If you are a complete newbie to MySQL click here. First you’re going to have to make a MySQL Database, and create a table called subscribers. This table should have 5 columns:

  • id – int(10) (Primary Key)
  • email – varchar(255)
  • validated – int(10)
  • ip – varchar(45)
  • vcode – varchar(255)

In PHPMyAdmin you can do this pretty easily with a nice user interface. However, if you have any problems with that or are using another system, then just run this query:

CREATE TABLE IF NOT EXISTS `subscribers` (
  `id` int(10) NOT NULL auto_increment,
  `email` varchar(255) NOT NULL,
  `validated` int(10) NOT NULL,
  `ip` varchar(45) NOT NULL,
  `vcode` varchar(255) NOT NULL,
  PRIMARY KEY  (`id`)
)

This should create a lovely little table in your MySQL database. Now we have to make a way to submit data to this table.

Subscribing

Make a couple of new file, and call them subscribe.php, resend.php and validate.php.

First, make a form so the user can submit data to the database:

<form method="get" class="form">
Enter your Email Here: <input type="text" value="" name="email" />
<input type="submit" value="Submit" />
</form>

This is pretty straight forward html. We’re just posting some data. Now that the data has been posted, we can begin to manipulate it. Above the form add the following:


<?php

mysql_connect("localhost", "username", "password") or die(mysql_error());
mysql_select_db("database") or die(mysql_error());

if($_GET['email']) {

}

?>

The first two lines just connect to the MySQL database. The if statement checks if the data has been posted, and if it has then do the whatever’s in the curly brackets, which we’ll get to now. So inside the curly brackets, add the following variables:

$email = $_GET['email'];
$ip = $_SERVER['REMOTE_ADDR'];

This puts the email the user submitted into a variable and gets the users IP Address. Next add the following line:

if(preg_match('/^[_a-z0-9-]+(\.[_a-z0-9-]+)*@[a-z0-9-]+(\.[a-z0-9-]+)*(\.[a-z]{2,3})$/i', $email)) {

That complicated string right there checks if the email is indeed an email, using preg_match. The code used here is Regexp, or regular expression, but lets not get into that. If that returns true, then we need to insert the email into the database. So first of all, lets run a query to check that the email isn’t already in the database:


$query = mysql_query("SELECT * FROM subscribers WHERE email = '".$email."'");

if(mysql_num_rows($query) == 0) {

                }
                else {

                }

Above we’re running a query and then counting the number of results with mysql_num_rows. If the number is equal to 0, then continue and submit the data to the database. Otherwise the email is already in the database, so there’s no point inserting it again. In the if(mysql_num_ro.. bracket, start by adding the following:

$key = "1234567890abcdefghijklmnopqrstuvwxyz";

$i = 0;
while($i < 15) {
$random[$i] = $key[mt_rand(0, strlen($key))];
$i++;
}
$implode = implode("", $random);

This generates a random key for the user, so that they can verify their email later on. $implode is the final key. A little low down on the code: $key is a variable consisting of the alphabet and numbers. We make $i equal 0, and make a while loop, which sets a random letter for every part of an array called random, numbered by $i. We then add 1 to i, and repeat the while loop 15 times. Implode turns an array into a string so we can use it more easily. Next I made a little message which will appear in the email:


$link = "http://www.webtint.net/email/validate.php?vcode=".$implode."";
$message = "Hello there,

Thank you for subscribing to our mailing list. By Subscribing to this you'll recieve spiffy updates on the latest happenings at Mail List PHP Script Inc.

To validate your email please click on the link below:
".$link."";

You’ll have to change the link to where ever validate.php is on your server. The link has to end with the ?vcode= bit so that we can define the user to validate their email. To finish it all off we do 3 things:

mail($email, "Validate your email", $message);
echo"<div class='message'>Alright. Well Done. Now Validate your Email.</div>";
mysql_query("INSERT INTO subscribers(email, ip, validated, vcode) VALUES('$email', '$ip', '0', '$implode')") or die(mysql_error());

We use the mail function to mail an email to the user, asking them to validate their email. We then echo a message to the user, saying that they ahve sucessfully subscribed, and finally, we insert the data into the database using a mysql query. Remember, the validated is always going to be 0 at this stage, because the email isn’t validated. In the else bracket, add the following:


echo"<div class='message'>You've already Subscribed! Need to validate your email? <a href='resend.php?email=".$email."'>Click here</a></div>";

This is just to give the user a message telling them that they’ve already subscribed, and if they need it, a link to resend their validation email. To finish off, close all the brackets, and add a final else statement, incase the user didn’t enter the email correctly.

}
}
else {
echo"<div class='message'>Failure. You didn't enter the email address correctly.</div>";
}
}

I added a little feature at the end, to check for the users IP Address and give them a little notice if they haven’t validated yet:


$query = mysql_query("SELECT * FROM subscribers");

while($row = mysql_fetch_array($query)) {

if($row[ip] == $_SERVER['REMOTE_ADDR'] && $row[validated] == 0) {

echo"<br /><div class='message'>Seems you haven't validated your email address yet. <a href='resend.php'>Click here to resend the email</a></div>";

}

}

Now the user can submit their details to the database, but we need a way for them to validate and resend the validation email if the mail function fails.

<h1>Resend my email!</h1>
Okay so in the cataclysmic event that the email doesn’t send, you don’t want your user to get angry and march off. So instead we need to make a page to resend this email. Start once again by connecting to your database:


mysql_connect("localhost", "username", "password") or die(mysql_error());
mysql_select_db("database") or die(mysql_error());

We’re going to be checking for two things this time in the opening if statement. We need to check that the user is posting something to the page, and that it’s an email.


if($_GET['email'] && preg_match('/^[_a-z0-9-]+(\.[_a-z0-9-]+)*@[a-z0-9-]+(\.[a-z0-9-]+)*(\.[a-z]{2,3})$/i', $_GET['email'])) {

}

Next we put the email into a variable (as we did in subscribe.php) and we get the validation code and whether or not the email is validated from the database, running a simple little query, all inside this first if statement.

$email = $_GET['email'];

$query = mysql_query("SELECT * FROM subscribers WHERE email = '".$email."' LIMIT 1");
while($row = mysql_fetch_array($query)) {
$vcode = $row['vcode'];
$valid = $row['validated'];
}

Next we’ll do a couple of checks. First, we’ll check that the email exists in the table, and that it is not validated. Else if it’s not, check if it is validated. Otherwise the email isn’t in the table, so we’ll tell the user that.

if(mysql_num_rows($query) > 0 && $valid == 0) {

}
elseif($valid == 1) {
echo"<div class='message'>Your email has already been validated!</div>";
}
else {
echo"<div class='message'>I'm afraid that email doesn't exist in our database. Try re-subscribing</div>";
}

The last two statements are pretty straight forward. The first if statement is where most of the stuff is going to happen, but it’s still pretty straight forward. It’s just a segment of the subscribe.php file.

$link = "http://www.webtint.net/email/validate.php?vcode=".$vcode."";
$message = "Hello there,

Thank you for subscribing to our mailing list. By Subscribing to this you'll recieve spiffy updates on the latest happenings at Mail List PHP Script Inc.
To validate your email please click on the link below:
".$link."";
mail($email, "Validate your email", $message);
echo"<div class='message'>Email has been resent!</div>";

Pretty straight forward huh? So lets assume the user has their email, and now they want to validate it. Well we’re going to need validate.php for that!

Validate me to pieces

Validate.php comes down to basically one thing, and that is changing a value from 0 to 1 in a database. Again, begin by connecting to your database:

  mysql_connect("localhost", "username", "password") or die(mysql_error()); mysql_select_db("database") or die(mysql_error());  

Then we need to check that a validation code has been sent in the url:

  if($_GET['vcode']) {  }  

Finally, insert all the guts of the if statement:

$vcode = $_GET['vcode'];
$query = mysql_query("SELECT * FROM subscribers WHERE vcode ='".$vcode."'");
if(mysql_num_rows($query) > 0) {
     mysql_query("UPDATE subscribers SET validated = '1' WHERE vcode = '".$vcode."'");
     echo"<div class='message'>Your email has been validated sucessfully!</div>";
}
else {
     echo"<div class='message'>Incorrect validation code!</div>";
}

All this does is checks if there is an email with the corresponding validation code, and if there is, validate that email. Otherwise it’s an incorrect validation code, and to tell the user that.

Okay so now the user can easily subscribe and validate their emails, but for you to be able to send them emails, we’re going to need some sort of admin type panel.

Admin Sending Emails

This is a pretty simple little script. Make a new file, called index.php, and put it in a folder called “admin”. Then make a form as shown below:

<form action="" class="form" method="post">
Title:<br /> 	<input type="text" name="title" value="" /><br /><br />
Message:<br /> 	<textarea name="message" rows="20" cols="75"></textarea><br /><br />
<input type="submit" value="Send to Everyone" /> </form>

Then above the form, again, connect to your mysql database:

mysql_connect("localhost", "username", "password") or die(mysql_error());
mysql_select_db("database") or die(mysql_error());

Next, to keep yourself right, you better check you’ve filled in the title and message fields!

if($_POST['message'] != "" && $_POST['message'] != "") {

}
else {
     if($_POST['message'] == "") {
          echo"<div class='message'>Please Enter a Message!</div><br />";
     }
     if($_POST['title'] == "") {
          echo"<div class='message'>Please Enter a Title!</div><br />";
     }
}

This just gives you a little error message if you’ve left one blank. In the first if statement, add the following:

$message = $_POST['message'];
$title = $_POST['title'];
$query = mysql_query("SELECT * FROM subscribers WHERE validated = '1'");
while($row = mysql_fetch_array($query)) {
     mail($row['email'], $title, $message);
}

echo"<div class='message'>Message sucessfully sent to everybody!</div>";

This mails all users with a validated email, and gives you a little message telling you it did it! You may want to password protect the admin folder. You can do this with a simple little htaccess script which you can find here.

I hope you’ve enjoyed this tutorial, and I hope in some way it has been useful.


Share This

 

 
 

Author: Johnny




Johnny is the owner of Webtint and usually the sole contributer to the site (apart from the ocassional guest post).


Comments



designfollow November 3, 2009 at 12:55 am

thanks for the great post


    Brodey November 22, 2009 at 1:33 pm

    Very good, But how would one add a custom email address like from ? I tried, but I cannot workout how to add a from ?


      Jonathan November 22, 2009 at 2:16 pm

      To add a from field with a custom email, simply change this line:
      mail($email, “Validate your email”, $message);

      to:
      mail($email, “Validate your email”, $message, “From: email@example.com“);


      Brodey January 1, 2010 at 9:27 am

      wow thankyou so much that fixed my problem and now I know how to add other things thankyou so very much big fan


Gopal Raju November 3, 2009 at 8:26 pm

Informative!


Maxi February 14, 2010 at 10:29 am

Good article man .thx


sohail June 5, 2010 at 2:45 am

its not working for me, I changed db details and link, I created database. what else I am supposed to do. ?

When I click on subscribe button, it showing blank page. email id comes in the url.





Leave us a Comment



Put your name here:

Your email goes here:

Got a Website? Put it here (optional):

And finally, your comment:




Sponsors