Jump to content


Check out our Community Blogs

Register and join over 40,000 other developers!


Recent Status Updates

View All Updates

Photo
- - - - -

PHP:Tutorial - Email Verification


  • Please log in to reply
8 replies to this topic

#1 John

John

    CC Mentor

  • Moderator
  • 4450 posts
  • Location:New York, NY

Posted 15 December 2006 - 06:10 PM

The first thing we are going to do is create a new php file and starte a new function that accepts an email parameter.


<?php
function EmailValidation($email) {

}
?>


Next thing we want to do is remove any unnecessary characters from the email address to prevent any melicious attacks. We do that by using the htmlspecialchars(), stripslashes(), and strip_tags() functions.


<?php
function EmailValidation($email) {
$email = htmlspecialchars(stripslashes(strip_tags($email))); //parse unnecessary characters to prevent exploits

}
?>


Next we are going to use regex in conjunction with the eregi (which is the same thing as the ereg function except eregi ignores case) to verify that the email address is in proper format. For example: name@domain.extention


<?php
function EmailValidation($email) {
$email = htmlspecialchars(stripslashes(strip_tags($email))); //parse unnecessary characters to prevent exploits

if ( eregi ( '[a-z||0-9]@[a-z||0-9].[a-z]', $email ) ) { //checks to make sure the email address is in a valid format

}
}
?>


Now we are going to explode the email address at the "@" sign so the parts of the email address are seperated into an array. That way we can use the domain name to make a connection to the server to test if the doman name is valid. To connect to the server we are going to use the fsockopen() function, and if the connection is established we are going to return true.


<?php
function EmailValidation($email) {
$email = htmlspecialchars(stripslashes(strip_tags($email))); //parse unnecessary characters to prevent exploits

if ( eregi ( '[a-z||0-9]@[a-z||0-9].[a-z]', $email ) ) { //checks to make sure the email address is in a valid format
$domain = explode( "@", $email ); //get the domain name

if ( @fsockopen ($domain[1],80,$errno,$errstr,3)) {
//if the connection can be established, the email address is probabley valid
return true;
}
}
?>


Now all we need to do is write the code for the even that the email address is not in a valid format or the connection cannot be established. We will set the return types to be false in these cases.


<?php
function EmailValidation($email) {
$email = htmlspecialchars(stripslashes(strip_tags($email))); //parse unnecessary characters to prevent exploits

if ( eregi ( '[a-z||0-9]@[a-z||0-9].[a-z]', $email ) ) { //checks to make sure the email address is in a valid format
$domain = explode( "@", $email ); //get the domain name

if ( @fsockopen ($domain[1],80,$errno,$errstr,3)) {
//if the connection can be established, the email address is probabley valid
return true;
/*

GENERATE A VERIFICATION EMAIL

*/

} else {
return false; //if a connection cannot be established return false
}

} else {
return false; //if email address is an invalid format return false
}
}
?>


Now that we have a function to verify the email address all you need to do is make a simple form like this


<?php
function EmailForm(){
if(empty($_POST['email'])){
echo "<form action=".$_SERVER['PHP_SELF']." method='post'>
<table border='0'>
<tr>
<td>Email</td>
<td><input name='email' type='text' id='email' /></td>
</tr>
<tr>
<td> </td>
<td><input type='submit' name='Submit' value='Validate' /></td>
</tr>
</table>
</form>";
} elseif(isset($_POST['email'])) {

if(EmailValidation($_POST['email'])) {
echo "An email has been sent to you. Please follow the instructions to activate your account.";
} else {
echo "Your email address appears to be invalid. Please try again.";
}

} else {

echo "An error has occured, please contact the administrator.";

}
}
?>


Now add these two functions to the same file and call the EmailForm function and your good to go.

<?php

function EmailValidation($email) {
$email = htmlspecialchars(stripslashes(strip_tags($email))); //parse unnecessary characters to prevent exploits

if ( eregi ( '[a-z||0-9]@[a-z||0-9].[a-z]', $email ) ) { //checks to make sure the email address is in a valid format
$domain = explode( "@", $email ); //get the domain name

if ( @fsockopen ($domain[1],80,$errno,$errstr,3)) {
//if the connection can be established, the email address is probabley valid
return true;
/*

GENERATE A VERIFICATION EMAIL

*/

} else {
return false; //if a connection cannot be established return false
}

} else {
return false; //if email address is an invalid format return false
}
}

function EmailForm(){
if(empty($_POST['email'])){
echo "<form action=".$_SERVER['PHP_SELF']." method='post'>
<table border='0'>
<tr>
<td>Email</td>
<td><input name='email' type='text' id='email' /></td>
</tr>
<tr>
<td> </td>
<td><input type='submit' name='Submit' value='Validate' /></td>
</tr>
</table>
</form>";
} elseif(isset($_POST['email'])) {

if(EmailValidation($_POST['email'])) {
echo "An email has been sent to you. Please follow the instructions to activate your account.";
} else {
echo "Your email address appears to be invalid. Please try again.";
}

} else {

echo "An error has occured, please contact the administrator.";

}
}

EmailForm();

?>

  • 2

#2 Guest_Jordan_*

Guest_Jordan_*
  • Guest

Posted 15 December 2006 - 06:57 PM

Very nice tutorial! Thank you!
  • 0

#3 xtraze

xtraze

    CC Devotee

  • Just Joined
  • PipPipPipPipPipPip
  • 872 posts

Posted 30 December 2006 - 12:25 AM

wow, not a simple for I say, but I may just copy/paste and I will Edit thing to suit my needs.
  • 0

#4 matthewk

matthewk

    CC Lurker

  • Just Joined
  • Pip
  • 2 posts

Posted 19 September 2007 - 09:19 AM

I think preg_match is quicker from what I've read. Also, what exploits could occur which require the necessity of htmlspecialchars?
  • 0

#5 JeanPierre

JeanPierre

    CC Lurker

  • Just Joined
  • Pip
  • 2 posts
  • Programming Language:PHP

Posted 08 November 2012 - 06:36 AM

Strarting from PHP 5.2.0 there is a build in PHP function that checks the validity of an email address:

if ($isemail=filter_var('bob@example.com', FILTER_VALIDATE_EMAIL))
{ echo "$isemail is a valid email address"; } else
{ echo "$isemail is no valid email address"; }

I've made a small piece of code which extends the standard PHP function with also domain checking.

http://www.wmappz.co...-email-address/
  • 1

#6 James360Smith

James360Smith

    CC Newcomer

  • Member
  • PipPip
  • 20 posts
  • Programming Language:Objective-C, PHP, JavaScript, PL/SQL, Ada, Transact-SQL, Logo, ActionScript
  • Learning:Objective-C, PHP, JavaScript, Perl, Ruby, PL/SQL, Visual Basic .NET

Posted 22 March 2013 - 03:23 AM

Basic but a most important tutorial for creating email verification functionality in PHP which almost required in each website to avoid spam or any suspicious activity. I like the way you presented here which anyone (beginner) can easily understand what's going on in the script.


  • 0

#7 JasonKnight

JasonKnight

    CC Addict

  • Senior Member
  • PipPipPipPipPip
  • 312 posts
  • Location:Keene, NH
  • Programming Language:C, C++, JavaScript, Delphi/Object Pascal, Pascal, Assembly, Others

Posted 26 April 2013 - 10:38 AM

Strarting from PHP 5.2.0 there is a build in PHP function that checks the validity of an email address

It is something of a laugh when people brute-force check things that PHP already has functions to handle.

"as of PHP 5.2" -- sounds a lot kinder than "as of 2006"

Though yours looks suspiciously like a stripped down version of the one I've been using for ~4 years or so...

My own function for checking it doesn't just go after MX, some valid mails only return an A record as they are actually using the parent/hosts MX.

filter_var also doesn't check for lengths.
 
function isValidEmail($address) {

	/* filter checks for valid chars, but not lengths */
	if (filter_var($address,FILTER_VALIDATE_EMAIL)==FALSE) {
		return false;
	}
	
	/* explode out local and domain for lengths */
	list($local,$domain)=explode('@',$address);
	$localLength=strlen($local);
	$domainLength=strlen($domain);
	
	return (
		/* check for proper lengths */
		($localLength>0 && $localLength<65) &&
		($domainLength>3 && $domainLength<256) &&
		(
			/* and then see if the domains are valid */
			checkdnsrr($domain,'MX') ||
			checkdnsrr($domain,'A')
		)
	);
	
} // isValidEmail
Use filter_vars to check for valid character sequence, manually check for valid lengths as per RFC 5321/5322, and then use a reverse lookup on the MX, if no MX check for A. (MIGHT want to also check for CNAME)

No brute force slash stripping or regex, no playing around with sockets on something that likely does NOT allow port 80 connects (seriously, a LOT of dedicated high traffic mail servers don't even HAVE HTTP servers on them!), while checking for the proper lengths and if they have registered mail exchange or primary addresses for the domain.

Edited by JasonKnight, 26 April 2013 - 10:40 AM.

  • 1
The only thing about Dreamweaver that can be considered professional grade tools are the people promoting it's use.

#8 lui0322

lui0322

    CC Lurker

  • New Member
  • Pip
  • 3 posts
  • Programming Language:C, C++, C#, PHP, (Visual) Basic
  • Learning:PHP, JavaScript, ActionScript, Others

Posted 16 May 2013 - 05:18 PM

i think there is something wrong with this code.. I agree to Mr. JasonKnight


  • 0

#9 naxez7

naxez7

    CC Lurker

  • New Member
  • Pip
  • 6 posts

Posted 16 September 2013 - 12:30 PM

Very nice tutorial, but I have two comments.

 

Your regexp has a couple of flaws:

[a-z||0-9]@[a-z||0-9].[a-z]

The way you have it set up is so it will match only to this format where x is any non uppercase letter or digit x@x.x. This will in fact probable never be the case and this will not match most email addresses.

 

This is the regexp I usually use in my code:

^\w+([\.-]?\w+)*@\w+([\.-]?\w+)+$

This has not failed on me yet, and it also allows TLDs. So the entire function would be

function checkValidMail ($email)
{
  $expr = "/^\w+([\.-]?\w+)*@\w+([\.-]?\w+)+$/";
  if (preg_match ($expr, stripslashes ($email)))
    return true;
  return false;
}

Otherwise if you wanted to check the email with regexp "correctly", here is the "correct" solution: http://www.ex-parrot...22-Address.html

Also most of the time, from what I've heard, email validation is just a useless hastle, sending verification emails with activation links is usually a preferred solution.


  • 0