News letter

Get Retire at 21's FREE Secrets to Making Money Online Ebook Today!

Find out how I'm going to Retire VERY Early Subscribe for my Free Secrets

Privacy Guaranteed. 100% Spam free.
Sponsor Video tutorials - We provide comprehensive tutorials for Dreamweaver MX, Dreamweaver MX 2004, Excel 2002, Flash MX, Flash 8, Photoshop 7, Photoshop CS, Photoshop CS2, Poker, VB.NET and Windows XP - geared for beginner to intermediate users.
Simple Email Validation
Learn how to use email verification to validate your users.
Category: Coding
Views: 8915

Simple Email Validation

Alright, in this tutorial I will teach you a small version of how to implement email verification for registration to a certain service, such as a newsletter, membership, etc.

Keep in mind this most probably isn't 100% secure, but it is about as close as it gets, other than serializing, hashing, and lengthening the code and all of that of course.


First, let's get a little preview at the code at hand that we will be working with.

<?php// Function checksfunction emailChecker($email){	global $check_result; // Make our result able to be used anywhere from the script	$check = "SELECT id FROM subscribers WHERE email = '$email'"; // Try to check the data against the database	$check_result = mysql_query($check) or die(mysql_error()); // Query or kill the script and print error	if(!mysql_num_rows($check_result))	return false; // If no results are found, return false	else	return true; // Otherwise, return true}function verificationChecker($email, $code){	global $check_result; // Make our result able to be used anywhere from the script	$check = "SELECT id FROM subscribers WHERE email = '$email' AND verification_code = '$code'"; // Try to check the data against the database	$check_result = mysql_query($check) or die(mysql_error()); // Query or kill the script and print error	if(!mysql_num_rows($check_result))	return false; // If no results are found, return false	else	return true; // Otherwise, return true}if(!$_POST){ // If no post data is present	if(!$_GET['email'] && !$_GET['code']){ // If no email and code are awaiting validation, give the form?>
Subscribe to our newsletter today!<br /><form method="POST" action="<?php echo $PHP_SELF; ?>">	Email: <input type="text" name="email" size="40" />	<br /><input type="submit" value="Subscribe!" /></form>
<?php	}	else{ // Otherwise, validate the email and code given by the link		$email = trim($_GET['email']); // Get the email		$code = trim($_GET['code']); // Get the code		if(!emailChecker($email)){ // Check if email is even awaiting validation			echo 'Error! Email Not Subscribed!<br />This email has not been signed up for verification.'; // Echo the problem		}		elseif(!verificationChecker($email, $code)){ // Then check if the code matches			echo 'Error! Invalid Verification Code!<br />Incorrect verification code.'; // Echo the problem		}		else{ // Otherwise, go ahead and verify the email			require('connect.php'); // Connect to the database			$id = mysql_result($check_result, 0, 'id'); // Get the id from our result in our checker functions			$verify_email = "UPDATE subscribers SET verified='TRUE' WHERE id = '$id'"; // Set the verified field to true			$result = mysql_query($verify_email) or die(mysql_error()); // Query or kill the script and print error			mysql_close(); // Close the database connection			echo 'Email Validated!<br />Your email has been verified by email You are now verified as a member!'; // Echo successful verification!		}	}}else{ // Otherwise, if there IS post data	require('connect.php'); // Connect to the database	function randomCode(){ // Random code function I found from a random zite =P		$alphabet = "abcdefghijklmnopqrstuvwxyzZ0123456789";		srand((double)microtime()*100000);		$i = 0; // Set $i for the loop		while($i <= 7){			$num = rand() % 27;			$a_Rand = substr($alphabet, $num, 1);			$security = $security.$a_Rand;			$i  ;		}		return $security;	}	$email = trim($_POST['email']); // Get the email address	$subject = 'Email Verification'; // Give a subject so the person knows what this email is about	$message = 'Thank you for your subscription request! To subscribe, simply click the link provided below.'; // Give some instructions as to what this is	$verification_code = randomCode().randomCode(); // Generate the random code twice, and string it together	$insert_unverified = "INSERT INTO subscribers VALUES(NULL, '$email', '$verification_code', 'FALSE')"; // Insert email and code into database	mysql_query($insert_unverified) or die(mysql_error()); // Query or kill the script	$message .= "nhttp://yoursite.com/subscribe.php?email=".$sendto.'&code='.$verification_code; // Give the link for the person to verify their account	mysql_close(); // Close the database connection		mail($sendto, $subject, $message); // Send the email!		echo 'A confirmation email has been sent to your email. Simply click the link in the email to verify your account.'}?>

It may look a tad intimidating now, but it really isn't if you take it one line at a time, and take note of the comments. This took longer to plan than it did to work with!

This is actually a very dumbed down version of the newsletter subscription script I coded that is available here at Webdesigndev!


First off though, we have to make sure we have a database set up for our subscriptions. A simple 3 column table will be exactly what we will need; one for an uto-incrementing id, one for email addresses, and one for the verification code. By now I am assuming you know how to do this.

Also, you will need to connect to the database with the mysql_connect() and mysql_select_db() functions. I assume you have this established, and always choose to make a seperate file for this so I can use it for any script on a site. In this example, I use the line require('connect.php'); so that the script will automatically terminate if the file cannot be found on the server (save the trouble of possibly echoing vital information if the connection wasn't established anyways!).

Alright, lets jump to it then!


First, we declate a few simple functions that will help us later on. We also open up the PHP tags.

To be honest, I found part of this function on a website which I cannot remember, and edited it a bit to make it simpler to understand.

<?php// Function checksfunction emailChecker($email){	global $check_result; // Make our result able to be used anywhere from the script	$check = "SELECT id FROM subscribers WHERE email = '$email'"; // Try to check the data against the database	$check_result = mysql_query($check) or die(mysql_error()); // Query or kill the script and print error	if(!mysql_num_rows($check_result))	return false; // If no results are found, return false	else	return true; // Otherwise, return true}function verificationChecker($email, $code){	global $check_result; // Make our result able to be used anywhere from the script	$check = "SELECT id FROM subscribers WHERE email = '$email' AND verification_code = '$code'"; // Try to check the data against the database	$check_result = mysql_query($check) or die(mysql_error()); // Query or kill the script and print error	if(!mysql_num_rows($check_result))	return false; // If no results are found, return false	else	return true; // Otherwise, return true}

The two are pretty much identical, only one checks for just the email, while the other checks both the email and the code.

Reading the comments, should be quite self-explanatory.

Now, let's open up the page by actually giving a form for the user to submit their email.

Before we do that however, we must check if there is POST data, because otherwise we would need to do something with that data.

if(!$_POST){ // If no post data is present

We then check that there is not an email and verification code to be validated, since we will be using GET data to validate the verification.

if(!$_GET['email'] && !$_GET['code']){ // If no email and code are awaiting validation, give the form

Alright, now we can display the form. For easy display, and for the sake of clarity, it is usually easier to exit the PHP code and print simple HTML so we don't have to sift through and escape any quotes, characters, etc.

?>
Subscribe to our newsletter today!<br /><form method="POST" action="<?php echo $PHP_SELF; ?>">Email: <input type="text" name="email" size="40" /><br /><input type="submit" value="Subscribe!" /></form>

Just a generic form with a text field for the email, and a submit button; nothing fancy.

Now that we have put up a form, and since we are still in an if conditional saying that no POST data is present, we might as well validate our email and code.

We start off by opening another PHP block and closing the last if conditional (the one our form should be displayed with if no email or verification data are present). We then set up an else statement, saying that if there is an email and verification code supplied in the URL, then we should start executing this code.

<?php	}	else{ // Otherwise, validate the email and code given by the link

Now, we will grab our email and code data from the URL, and use the trim function just to make sure no extra spaces were slapped on somehow.

$email = trim($_GET['email']); // Get the email$code = trim($_GET['code']); // Get the code

Now, we will first make sure the email is even in the database and waiting for verification, using our handy little function we defined earlier.

if(!emailChecker($email)){ // Check if email is even awaiting validationecho 'Error! Email Not Subscribed!
This email has not been signed up for verification.'; // Echo the problem}

If it is, then we check to make sure the verification code is correct with our other handy function we defined earlier.

elseif(!verificationChecker($email, $code)){ // Then check if the code matchesecho 'Error! Invalid Verification Code!
Incorrect verification code.'; // Echo the problem}

Alright, now if this block proves false, then the email and code pair are valid, so we can go ahead and verify them.

We also close up the conditional saying that email and code data needed validation, and the conditional saying that there is no POST data present.

else{ // Otherwise, go ahead and verify the emailrequire('connect.php'); // Connect to the database$id = mysql_result($check_result, 0, 'id'); // Get the id from our result in our checker functions$verify_email = "UPDATE subscribers SET verified='TRUE' WHERE id = '$id'"; // Set the verified field to true$result = mysql_query($verify_email) or die(mysql_error()); // Query or kill the script and print errormysql_close(); // Close the database connectionecho 'Email Validated!
Your email has been verified by email You are now verified as a member!'; // Echo successful verification!}}}

First, we simply connect to our database, and find out what the id of the successful query was back when we were validating the code with the functions earlier defined. We then set up a query to update our 'verification' column, to say that the user has been successfully verified. We then close the database connection, and echo the success.


We're almost there! Now all we have to do is send an email and generate a verification code for them.

First we must open a connection to our database. Also here, we can use a randomizer function. A quick search on Google will give you plenty of good random code functions, but I chose this one for its simplicity. It may not be the most random out there, but it works for me.

require('connect.php'); // Connect to the databasefunction randomCode(){$alphabet = "abcdefghijklmnopqrstuvwxyzZ0123456789";srand((double)microtime()*100000);$i = 0;while($i <= 7) {$num = rand() % 27;$a_Rand = substr($alphabet, $num, 1);$security = $security.$a_Rand;$i  ;}return $security;}

This is one of the only parts of the code I cannot explain 100%. A quick Google search may result in the forum I found this function from. All that matters here is it generates a random code 8 digits long.

This next block of code is simply setting some variables for our email, such as where to send it, the subject, and our message.

$email = trim($_POST['email']); // Get the email address$subject = 'Email Verification'; // Give a subject so the person knows what this email is about$message = 'Thank you for your subscription request! To subscribe, simply click the link provided below.'; // Give some instructions as to what this is

Now, we will take our randomCode() funtion and make a random code for our verification code. I chose to do it twice and string it together, just for the heck of it. You can choose to do whatever function or method you want to randmize your code more if you need.

$verification_code = randomCode().randomCode(); // Generate the random code twice, and string it together

Now we can make our query. Here we are simply inserting the email, verification code, and a 'FALSE' to our verified column.

$insert_unverified = "INSERT INTO subscribers VALUES(NULL, '$email', '$verification_code', 'FALSE')"; // Insert email and code into databasemysql_query($insert_unverified) or die(mysql_error()); // Query or kill the script

Now we can give the person the link in order to verify their account. It simply takes the email and verification code and puts it into the URL for the script to retrieve it and check it, which we already did in the last conditional. We can also now close our database since we won't need it anymore.

$message .= "nhttp://yoursite.com/subscribe.php?email=".$sendto.'&code='.$verification_code; // Give the link for the person to verify their accountmysql_close(); // Close the database connection

Almost done! Now all we have to do is email the verification email, and echo a success! Then we can close our last conditonal, and our PHP block.

mail($sendto, $subject, $message); // Send the email!echo 'A confirmation email has been sent to your email. Simply click the link in the email to verify your account.'}?>

And we are now done!

Try and experiment, and have fun verifying your members before they sign up for your services!

For extra credit, make email verification for unsubscription too!


If you would like more help with this tutorial please register and visit the forum.



Bookmark with:              
  Add to Favorites    Google Bookmark
  Delicious   Digg
  reddit  Stumble Upon

Recommended Money Makers

The Reverse Funnel System!

“I'm About To Share With A Select Few, The Exact Details Of My Simple And Proven 'Reverse Funnel System™' That Quickly And Simply Puts $5,000 to $10,000 In Many Students' Pockets EVERY WEEK!”

  • Systems Work, People Fail...It's that simple!
  • You've heard the success stories...Now it's your turn to become one.
  • Utilize my ads, my marketing co-opps & my proven system.

Find out More...

:: About Michael

Michael DunlopAbout Michael

“But I am already older than 21”, I hear you cry. Don’t worry, despite the name, the information and advice is more geared towards retiring prior to having a fake hip installed.

Find out more about Michael...

:: Website Sponsors
:: Recommended Money Maker

Blogging all the way to the Bank!

- Six Figure Blogging Made Easy - Create Real Blogs In Just A Few Minutes. - How I make $35,000 every month!
Exposed... How to make your blogs earn money on almost autopilot.

:: Latest Blog Posts
:: Vote Poll
Who is your favourite Entrepreneur?
 
Bill Gates
Richard Branson
Alan Sugar
Donald Trump
Steve Jobs
 
    
Total Votes:  4454
:: Other Links