PHP Email validation

Wang191

[H]ard|Gawd
Joined
Nov 30, 2000
Messages
2,026
I found an email validation script that I wanted to use but I'm encountering a problem. When it finds an email address that it can't validate it seems to error out instead of returning false. Can any of you spot why that's happening.
PHP:
function check_email_address($email) {
			  // First, we check that there's one @ symbol, 
			  // and that the lengths are right.
			  if (!ereg("^[^@]{1,64}@[^@]{1,255}$", $email)) {
				// Email invalid because wrong number of characters 
				// in one section or wrong number of @ symbols.
				return false;
			  }
			  // Split it into sections to make life easier
			  $email_array = explode("@", $email);
			  $local_array = explode(".", $email_array[0]);
			  for ($i = 0; $i < sizeof($local_array); $i++) {
				if
			(!ereg("^(([A-Za-z0-9!#$%&'*+/=?^_`{|}~-][A-Za-z0-9!#$%&
			?'*+/=?^_`{|}~\.-]{0,63})|(\"[^(\\|\")]{0,62}\"))$",
			$local_array[$i])) {
				  return false;
				}
			  }
			  // Check if domain is IP. If not, 
			  // it should be valid domain name
			  if (!ereg("^\[?[0-9\.]+\]?$", $email_array[1])) {
				$domain_array = explode(".", $email_array[1]);
				if (sizeof($domain_array) < 2) {
					return false; // Not enough parts to domain
				}
				for ($i = 0; $i < sizeof($domain_array); $i++) {
				  if(!ereg("^(([A-Za-z0-9][A-Za-z0-9-]{0,61}[A-Za-z0-9])|
				  ?([A-Za-z0-9]+))$",$domain_array[$i])) {
					return false;
				  }
				}
			  }
			  return true;
}

it's failing just before the last return false statement.
PHP:
				for ($i = 0; $i < sizeof($domain_array); $i++) {
				  if(!ereg("^(([A-Za-z0-9][A-Za-z0-9-]{0,61}[A-Za-z0-9])|
				  ?([A-Za-z0-9]+))$",$domain_array[$i])) {
					return false;

When the email address is good it returns true perfectly.
 
What is the error message you are getting? Also ereg() is deprecated as of PHP 5.3 according to PHP.net
 
It was trying to return text before the headers so I was getting that whitespace error plus this one:
"ereg() [function.ereg]: REG_BADRPT in..."

i added ob_start to the top of my page to get past the error and see what would happen. That's when i noticed the function would just fail and return nothing. And then the rest of the scripts on the page kept going (albeit incorrectly because this didn't return a true or a false). When i put in a bad email address this process would take about a minute. when I put in a good email everything would work perfectly fine and execute in under a second.

The strange part is that I removed the ob_start and I can't get the error to show on screen anymore. The script is still behaving poorly...i just can't get the written error to present itself.
 
I did notice that php.net said it was no longer in use. I'm not quite sure how to fix that yet...I'm not exactly proficient at php yet and for some of this more advanced programming I still have to hack other people's code before I understand it myself. So right now I don't really understand how to implement the new usage of the function yet.
 
fightingforalostcause had a link with updated methods.

this seems to work well:
PHP:
    function check_email_address($email) {
            $valid = preg_match("/^([\w\!\#$\%\&amp;\'\*\+\-\/\=\?\^\`{\|\}\~]+\.)*[\w\!\#$\%\&amp;\'\*\+\-\/\=\?\^\`{\|\}\~]+@((((([a-z0-9]{1}[a-z0-9\-]{0,62}[a-z0-9]{1})|[a-z])\.)+[a-z]{2,6})|(\d{1,3}\.){3}\d{1,3}(\:\d{1,5})?)$/i", $email);
     
            if($valid){
                    $domain = explode("@",$email);
                    if(checkdnsrr($domain[1]))
                            return true;
                    return false;
            }
            return false;
    }
 
I'll add this in here for anyone doing future searches: http://www.php.net/manual/en/function.filter-var.php

PHP has a built in function to handle email validation as of 5.2.0, although it doesn't check for a live domain as your solution does. Still, filter_var($email_a, FILTER_VALIDATE_EMAIL) is quite a bit easier than your regular expression, and you can always yank the domain off the end of that and do your tests afterwards.

I'm thinking mainly of future maintenance.
 
I'll add this in here for anyone doing future searches: http://www.php.net/manual/en/function.filter-var.php

PHP has a built in function to handle email validation as of 5.2.0, although it doesn't check for a live domain as your solution does. Still, filter_var($email_a, FILTER_VALIDATE_EMAIL) is quite a bit easier than your regular expression, and you can always yank the domain off the end of that and do your tests afterwards.

I'm thinking mainly of future maintenance.

I was having trouble getting that to work. It seemed to want to return some kind of a text value. It kept causing errors since it was trying to return text above the header. Also, I could not seem to get it to return true or false the way I thought it should. I'm sure it user error but I do like that the solution I have checks DNS.

The real beauty of the DNS check is that it only has to do a DNS check once during registration. The site I am building sends emails to users. So if a user tried to send an email to another user they would have to wait for an emails script to finish sending. By doing the check once, I can make it faster for the users later on. In truth, I do a second check before sending the email from the user but since it's validated during registration it is more likely that it will still be a valid address. It's possible an email domain bit the dust but it would not be the case a majority of the time.
 
I was having trouble getting that to work. It seemed to want to return some kind of a text value. It kept causing errors since it was trying to return text above the header. Also, I could not seem to get it to return true or false the way I thought it should. I'm sure it user error but I do like that the solution I have checks DNS.

Script or bust.

php.net said:
Return Values

Returns the filtered data, or FALSE if the filter fails.

So you'd obviously need to check for false only.
Code:
if(filter_var($email,FILTER_VALIDATE_EMAIL) !== false) {
     //email is valid
}
 
another vote for filter_var. Regular Expressions make my head hurt.
 
Email validation is one of those things where you really want to use one regular expression or function, but in practice the best solution is the following:

- If you need to confirm an email, send a email to the address provided, if data never comes back well it was probably a fake email address.

- If you need to check to see if someone is putting in an email address before sending said email, all you need to check for are two things separated by at most 1 '@', or the following regex: '/^[^@]+@[^@]+\.[^@]+$/'

Hope this helps. By the way you should be using preg now instead of ereg as it is deprecated. http://us2.php.net/manual/en/ref.pcre.php
 
Doesnt HTML5 do email validation?

Don't know, but even if it did, relying on browser-side validation does not guarantee that the validation will be done...

Yes, you can assign regex validation to input elements with the upcoming HTML 5 spec, however HTML 5 does not exist yet so using any of its features is not a good idea until the standard becomes ratified and different browsers pick how to use it. With that said I'd like to reiterate krogen's point that you MUST always validate on the server side. The easiest way to break your program is from user input not being validated.
 
Back
Top