Jump to content
MakeWebGames

[FAQ] Email Validation in PHP


Spudinski

Recommended Posts

Since the ops thought this should be made, I'll talk about this topic.

Email Validation is a common thing that is done on all/most signup pages, doesn't matter which website it may be.

These types of scripts are not that hard to create, but most struggle to make it.

Another thing with most email validation scripts is that it is inaccurate, you can enter something like [email protected] and it will return as a valid email address, here is a script just as that, feel free to check my theory(this is the fourth result from googling "Email validation PHP").

This is because of poor validation, normally something like the following is used in most validation scripts:

ereg("^[a-zA-Z0-9_]+@[a-zA-Z0-9\-]+\.[a-zA-Z0-9\-\.]+$]", $email)

It is not only done in PHP, but also in Javascript, most people think that form validation with javascript is good, but they are just so wrong.

I suggest reading this article if you already know how to develop in PHP, you can make your own then - http://www.ilovejackdaniels.com/php/ema ... alidation/

In this post, I will be giving examples of a few types of email validation script that can be used in PHP.

 

Example 1

This will look at the email address, split it up into a username, domain name and a suffix.

<?php
function validate_mail($address) {
if (!ereg("^[^@]{1,64}@[^@]{1,255}$", $address)) return false;
else {
	$email_parts = explode('@', $address, 2);
	$domain_parts = explode('.', $email_parts[1]);
	for ($i = 0; $i < count($local_array); $i++) {
		if (!ereg("^(([A-Za-z0-9!#$%&'*+/=?^_`{|}~-][A-Za-z0-9!#$%&'*+/=?^_`{|}~\.-]{0,63})|(\"[^(\\|\")]{0,62}\"))$",
		$local_array[$i])) {
			$returned = true;
			return false;
		} 
	}
	if (empty($returned) && (ereg("^\[?[0-9\.]+\]?$", $email_parts[1]) || count($x = explode('.', $email_parts[1])) < 2)) {
		return false;
	}
	else {
		for ($i = 0; $i < count($domain_array); $i++) {
			if (!ereg("^(([A-Za-z0-9][A-Za-z0-9-]{0,61}[A-Za-z0-9])|([A-Za-z0-9]+))$", $domain_parts[$i])) {
				$returned = true;
				return false;
			}
		}
	}
	if (empty($returned)) return true;
}
}
?>

 

Example 2

Doing a basic check if the email is valid, and then sending a email to the user, where they will find a link to activate their account.

This is the long way around, and requires much more things to be done, like making an extra row in the user table(I'm going to skip the mysql parts).

 

<?php

function valemail($address, $username, $password, $subject, $mail_message, $headers) {
if (!ereg("^[^@]{1,64}@[^@]{1,255}$", $address)) return false;
else {
	if (empty($username) || empty($password)) return false;
	else {
		$mail = mail($address, $subject, $mail_message, $headers);
		if (!empty($mail)) return false;
		else return true;
	}
}
}

?>

Using the function is very simple.

You can use both of the examples together, to make an even more accurate validation, but it is optional.

Here is a example for each of the two examples:

Example 1

<?php

if (!empty($_POST['address'])) {

$headers = "From: [email][email protected][/email]ix <group youdomain>\r\nReply-to: [email][email protected][/email]ix\r\n";
$content = "Thank you for signing up at our website.\r\n 
		   	   In order for you to login to your account, you will first need to activate your account.\r\n\r\n
		   	   Please verify that the following information is correct before you continue:\r\n
		   	   Account: $username\r\n
		   	   Password: $password\r\n
		   	   \r\nIf all of the above information is correct, please continue by following the link below.\r\n
		   	   $validate_link (<a href=\"$validate_link\">AOL</a>)\r\n\r\n 
		   	   If you did not create this account, please follow the link below.\r\n 
		   	   $suspend_link (<a href=\"$suspend_link\">AOL</a>)\r\n\r\n\r\n
		   	   Regards,\r\n
		   	   YourDomain";

$subject = 'Account Signup: ' . $username;
$filename = $username . md5($address);
$key = sha1($filename);
$fp = fopen($dir . '/' . $key, 'w');
fputs($fp, base64_encode("INSERT INTO `users` (`id`, `name`, `email`, `password`) VALUES (NULL, '" . 
$username . "', '" . $address . "', '" . $password . "')"));
fclose($fp);

$result = valemail($_POST['address'], htmlspecialchars($_POST['name']), $_POST['password'], $subject, $content, $headers);
if (empty($result)) echo 'We were unable to verify your email address.';
else echo 'We have sent an email to the address you specified, please review the message and follow the instructions.';
}
else if (count($url = explode(':', $_SERVER['QUERY_STRING'])) == 2) {
switch ($url[0]) {
	case 'act' : 
			$result = valaccount($url[1]);
			 if (strlen($key) != 32 || empty(file_exists($dir . '/' . $key))) {
			 	echo 'You have supplied an invalid activation key.';
			 }
			 else {
				$fp = fopen($dir . '/' . $key, 'r');
				$contents = '';
				while(!feof($fp)) $contents .= fgets($fp, 1024);
				fclose($fp);
				unlink($dir . '/' . $key);
				$contents = base64_decode($contents);
				$split = explode('_.', $contents);
				if ($split[0] <= (time()-1800)) {
					echo 'Your activation has expired.';
				}
				else {
					$query = mysql_query($split[1]);
					if (empty($query)) {
						echo 'Your account has been activated!
You may no' . 
						'w proceed to the login page.';
					}
				}
			}
			break;
	case 'spd' : unlink($dir . '/' . $key); break;
	default : echo 'Invalid request.'; break;
}							 
}
else {
echo '

<form method="post">
 	 Name: <input name="name">

 	 Password: <input name="password">

 	 Email: <input name="address">

 	 <input type="submit" value="validate">
 	 </form></p>';
}

?>

 

If you have any questions, please reply to this thread.

Edit: Updated functions.

Link to comment
Share on other sites

Re: [FAQ] Email Validation in PHP

I might have missed it as I'm still asleep......

I check on the MX record for e-mail validation

here is my function

 

function myCheckDNSRR($hostName, $recType = '')
{
   if(!empty($hostName)) {
       if( $recType == '' ) $recType = "MX";
       exec("nslookup -type=$recType $hostName", $result);
               foreach ($result as $line) {
           if(eregi("^$hostName",$line)) {
               return true;
           }
       }
               return false;
   }
   return false;

 

Now what does it do

if you get eg [email protected] it will check if there is a mail server on yourdomain.tld

it's simple and effective but might not be failsafe

Link to comment
Share on other sites

Re: [FAQ] Email Validation in PHP

 

Shoudlnt your code be:

function myCheckDNSRR($hostName, $recType = '')
{
   if(!empty($hostName)) 
    {
       if($recType == '' )
        { 
           $recType = "MX";
        }
       exec("nslookup -type=$recType $hostName", $result);
       foreach ($result as $line) 
        {
           if(eregi("^$hostName",$line)) 
            {
               return true;
            }
        }
               return false;
    }
   return false;
}

 

Its easier for me to read that and it's got the end loop (}) added.

Link to comment
Share on other sites

  • 2 months later...

Re: [FAQ] Email Validation in PHP

just an interjection ->

there's really no point in checking the mx record if your sending an email validation to the user anyway.

if they put a false email they obviously won't be able to verify it. in addition to exec(); not being enabled on all hosts, mail uses less load :)

Link to comment
Share on other sites

Guest Anonymous

Re: [FAQ] Email Validation in PHP

Not sure I can fully agree with this... Take one particular example...

One organization I'm involved with is currently sending out mails to around 15,000 clients. Now to reduce the load on the servers, the mail server is configured to trickle feed these mails over a day or so. Now, we know that not all addresses will have valid domain parts - due to companies closing down, ISPs vanishing of the face of earth etc.

Exim (my mail server of choice) can be setup in various ways - notably to attempt a retry, if there is no response, which could mean there well be a fair of data in it's "stack" over the next 3-4 days. Performing a swift getmx would reduce the number of attempts made by the mail server -- in this case we've seen approx 2,000 bounces.

In my mind therefore, this would save a bit of load - I agree, perhaps on small jobs, just send a mail out, but once you start reaching the realms of small to large (this particular one being small) mailshots, I'd be looking at some optimization.

Link to comment
Share on other sites

Re: [FAQ] Email Validation in PHP

my statement was reliant on a small user base. yes, if your sending out 15,000 emails: you'd probably want some protection. considering this is a php-gaming community, the snippet at hand was to validate email addresses ( one could assume for registration ); i don't know of any php-game that has 15,000 users signing up at once. in addition, if you wanted to take it a step further, what if someone signed up with @google.com or @microsoft.com or @abcd.com -> all would validate but, chances of someone having those emails is very unlikely; which would also cause bouncebacks, so it's kinda a loss-loss. imo, instead of preforming double the work to validate, mail(); then possibly receive bounceback, it would be more optimal to simply mail(); has have the possibility to bounceback.

just my opinion :-)

Link to comment
Share on other sites

Re: [FAQ] Email Validation in PHP

 

my statement was reliant on a small user base. yes, if your sending out 15,000 emails: you'd probably want some protection. considering this is a php-gaming community, the snippet at hand was to validate email addresses ( one could assume for registration ); i don't know of any php-game that has 15,000 users signing up at once. in addition, if you wanted to take it a step further, what if someone signed up with @google.com or @microsoft.com or @abcd.com -> all would validate but, chances of someone having those emails is very unlikely; which would also cause bouncebacks, so it's kinda a loss-loss. imo, instead of preforming double the work to validate, mail(); then possibly receive bounceback, it would be more optimal to simply mail(); has have the possibility to bounceback.

just my opinion  :-)

If you were talking about the "small user"'s, then there should be no "load" on the server.

I've seen PHP-Games that has very big account databases, it isn't impossible, so what if you are sending something as simple as a newsletter.

Take Nyna's example, you would validate first, and if validation succeeds, then you would send a mail.

This is because a large percentage of the "php-game"'s accounts have invalid email addresses.

But as you said threeZ, email accounts are assumed to be checked in the sign-up process, and then marked valid, but by the time a "php-game" reaches "15,000" accounts, some email addresses might have changed.

Edit: reading mdshare's post now.

Link to comment
Share on other sites

Re: [FAQ] Email Validation in PHP

you're trying to prove a point ( that im wrong ) and im trying to express my opinion.

verywell: you still didn't address two big points of mine

1 ) automatic validation upon @google.com, @microsoft.com, @abcd.com, @nasa.gov

2 ) exec(); not enabled

really there's nothing you can do about either situation. maybe a filter ( not the best solution to anything )

or maybe curl/wget/file_get_content some unreliant site for a mx lookup

IN MY OPINION: as previously stated, i believe it would be more load efficient to just send the email, and await bounceback than validate the mx record ( which could validate anything ), send the email, then await bounceback.

 

so what if you are sending something as simple as a newsletter...

But as you said threeZ, email accounts are assumed to be checked in the sign-up process, and then marked valid, but by the time a "php-game" reaches "15,000" accounts, some email addresses might have changed.

wouldn't you give the user the option to change their registered email via the options within the game.

also, you're going outside the scope of the provided snippet -> email validation upon registration.

Link to comment
Share on other sites

Re: [FAQ] Email Validation in PHP

 

you're trying to prove a point ( that im wrong ) and im trying to express my opinion.

We are also just expressing our opinions, this is a freedom of speech community.

 

1 ) automatic validation upon @google.com, @microsoft.com, @abcd.com, @nasa.gov

A partial solution is to connect to the mail server and request confirmation, still not completely everything, but a script also can't be 100% secure.

 

2 ) exec(); not enabled

If you have active 15,000 accounts, you would most likely already have your own server to run things.

 

IN MY OPINION: as previously stated, i believe it would be more load efficient to just send the email, and await bounceback than validate the mx record ( which could validate anything ), send the email, then await bounceback.

I'm quite sure that that would result in more of a "load" than just checking the MX record at the beginning.

 

wouldn't you give the user the option to change their registered email via the options within the game.

also, you're going outside the scope of the provided snippet -> email validation upon registration.

Not everyone account will do that, and also, inactive accounts.

Link to comment
Share on other sites

Guest Anonymous

Re: [FAQ] Email Validation in PHP

Why do you need exec ?

Killah's notion of using nslookup, well, it works, but again it's context switching and as you rightly point out, exec is not always available (although, why anybody would choose a host with restricted features is ... well, for another topic).

getmxrr() available in both PHP 4 and 5 will perform the job nicely IIRC.

As for auto-validation vs. large domains - okay, although I will point out (with tongue firmly in cheek), as you pointed out so eloquently ""considering this is a php-gaming community"" one wonders how many people from nasa.gov we are going to get ;)

Link to comment
Share on other sites

Re: [FAQ] Email Validation in PHP

 

A partial solution is to connect to the mail server and request confirmation, still not completely everything, but a script also can't be 100% secure.

result would be the same.

 

If you have active 15,000 accounts, you would most likely already have your own server to run things.

very untrue.

 

I'm quite sure that that would result in more of a "load" than just checking the MX record at the beginning.

theoretically, no.

 

Not everyone account will do that, and also, inactive accounts.

again: scope of snippet...

Comments: this is an awkward way to reply

 

getmxrr() available in both PHP 4 and 5 will perform the job nicely IIRC.

As for auto-validation vs. large domains - okay, although I will point out (with tongue firmly in cheek), as you pointed out so eloquently ""considering this is a php-gaming community"" one wonders how many people from nasa.gov we are going to get ;)

getmxrr(); -> very good point out. my retort was based on the supplied code :)

in responce to "one wonders how many people from nasa.gov we are going to get" -> probably as many as you would get for the need to validate an mx record. if everyone used a valid address there would be no need ;)

Link to comment
Share on other sites

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Paste as plain text instead

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • Create New...