Jump to content
xisto Community
Sign in to follow this  
Sadas

How To Check Email Adress And Name Validity? Refusing wrong info in a form...

Recommended Posts

Hello there! I'm learning php and MySQL these days... Here I've got a little script I'm playing with...

<?phpif ($submit == "click"){   $connection = mysql_connect (localhost, username, password);  if ($connection == false){    echo mysql_errno().": ".mysql_error()."<BR>";    exit;  }     $query = "insert into email_info values ('$fullname', '$email')";  $result = mysql_db_query ("sadas_Testing", $query);  if ($result){    echo "Success!";  }  else{    echo mysql_errno().": ".mysql_error()."<BR>";  }  mysql_close ();}else{  echo "    <html><body>    <form method=\"post\" action=\"testing.php\">    Enter your full name    <input type=\"text\" name=\"fullname\"></input><br>    Enter your email address    <input type=\"text\" name=\"email\"></input><br>    <input type=\"submit\" name=\"submit\" value=\"click\"></input>            </form>    </body></html>  ";}?>

It writes people names and email adresses in MySQL database. My goals is to make the script:
1) refuse not valid email adresses;
2) refuse not full names (there should be at least two words in full name field, containing only letters).

Share this post


Link to post
Share on other sites

Yeah, I know that...

I should make tha script to look for something like this:

XX@XX.XX

X means a letter or a number

There may be no more than one "@", but can be more than one "." Difficult...

Or maybe there are some webpage providing such services. I'm wondering becouse I've seen such scripts refusing wrong adresses many times...

Share this post


Link to post
Share on other sites

    <html><body>    <form method=\"post\" action=\"testing.php\">
    Enter your full name
    <input type=\"text\" name=\"fullname\"></input><br>
    Enter your email address
    <input type=\"text\" name=\"email\"></input><br>
    <input type=\"submit\" name=\"submit\" value=\"click\"></input>       
    </form>
    </body></html>


its easier for email check using javascript and checked again using php (client & server side)

split fullname into 2 input than check each one of them . if must, u can merge those input .


Oncom Beureum
The Best Place in the City

Share this post


Link to post
Share on other sites

Thanks... It looks like that java scripting comes into my learning campaign too...I'll try to make the whole script working in one piece and let you know how I'm doing. :(

Share this post


Link to post
Share on other sites

I found a similar way to do it in php here. This one checks to make sure the syntax is correct as well as checking to make sure the domain for the address they entered is registered with a MX (mail exchange) record in DNS. Basically, it makes sure there's a mailserver running at that domain. The documentation on that php function can be found here. Here's the code for the php function to validate an email address:

function validate_email($email){   // Create the syntactical validation regular expression   $regexp = "^([_a-z0-9-]+)(\.[_a-z0-9-]+)*@([a-z0-9-]+)(\.[a-z0-9-]+)*(\.[a-z]{2,4})$";   // Presume that the email is invalid   $valid = 0;   // Validate the syntax   if (eregi($regexp, $email))   {      list($username,$domaintld) = split("@",$email);      // Validate the domain      if (getmxrr($domaintld,$mxrecords))         $valid = 1;   } else {      $valid = 0;   }   return $valid;}

And it returns a boolean so you could use it like this:
if (validate_email($email))   echo "Email is valid!";else   echo "Email is invalid!";

Share this post


Link to post
Share on other sites

Here's a post regarding me searching for the best method of email validation, one thing that may need to be altered is the length check. Which is what I never found while reading the RFCs on the situation.

http://forums.xisto.com/topic/80809-topic/?findpost=

As with your script, it needs to be secured a bit more, there's no checks on user input, this is by far the worse thing that you could let run by. You may also want to make the script more uptodate with whatever version you're running of PHP, if it's greater than 4.0 then you should work on making it compatible for that, avoid PHP 5 for now till it's more mainstream.

I can help you on this, my email script in the above post is good from my point of view, it will check validity, but it won't check existence, that's something else we need to do.

We can do that easily, by sending out a confirmation email, if it's not validated within 7 days, we should remove that entry.

With full names, it's basically a similar method to the email validation, yet we make sure that information that's entered is stripped of all slashes, etc.

We need to fix up the query string for the database, we've left doors open for SQL Injection and that's not a good thing, that's why we must perform checks on the data first before trying to store it in the database.

There's also other things like making sure the form isn't tampered with, making sure it's being sent from the right location, etc.


Cheers,


MC

Share this post


Link to post
Share on other sites

OK, let's try to develope valid email input into MySQL database script then.
We should begin with writing function to validate email. Let's look at your array of matches:

/^[a-z][a-z0-9_.-]+@[a-z0-9][a-z0-9-]+\.[a-z]+(\.[a-z]+)*$/i
What about email adress with IP instead of domain, something like this:

john@87.243.154.12

Would your code allow it? :D I found here some big script with explanation, so we could use some ideas from it... But I think the best way would be simply to check two main things: if email has "@" and at least one "." and then send confirmation email with some code to confirm. Entry would be added to MySQL only then, when confirmation code would be received.
I'm suggesting that becouse we don't know if there are email adresses breaking the rules of RFC 2822. More of that, with IPv6 it's possible to have IPs like this:

2014:5107:45c7:d::a05:66
I wonder can it be used instead domain or not...
email adress would be really strange:
john@2014:5107:45c7:d::a05:66 (how about validating that? :()

So what do you think?

Share this post


Link to post
Share on other sites

Hey Sadas, thanks for the link above.This guy has saved me a lot of work tracking down specific information. However IPv6 is not checked for in this, and I've read in the RFC that IPv4 and IPv6 are valid, but the preferred method is domain or more correctly Fully Qualified Domain Name (FQDN).What I don't understand is he's saying what is valid and what is not, then in his script he's not actually testing for what he said, he's just testing in general. Especially overlooking the formatting of how a username can appear at the beginning of an email.I would have been more impressed if he had actually worked on what's valid and what's not. Which is the whole reason for a validator, and hopefully all MTAs have all got a method of validating whether the address is formed correctly or not. Might save me even more effort in reading the RFCs further if I can just find that part of the code.Cheers,MC

Share this post


Link to post
Share on other sites

function valid_name($name){ // return FALSE if it contains characters which // which ARNT on the specified list if(ereg('[^[:space:]a-zA-Z0-9_.-]{1,}', $name)) { return false; } else { return true; }}andif (eregi("^[A-Z0-9._%-]+@[A-Z0-9._%-]+\.[A-Z]{2,6}$", $email)) { echo "'$email' is a valid email!";}

Share this post


Link to post
Share on other sites

There can be no dots at all in the address. For example marksmann1@localhost lol xD But there are real cases when the aren't any dots

-reply by marksmann1

Share this post


Link to post
Share on other sites

I came across this email validation script about a year back on google but have been unable to find the group that created it since, although it seems to be a very popular script now. It is probably the best way to verify an email address is valid.

class EmailAddressValidator {  /** * Check email address validity * @param   strEmailAddress	 Email address to be checked * @return  True if email is valid, false if not */ public function check_email_address($strEmailAddress) {  // If magic quotes is "on", email addresses with quote marks will // fail validation because of added escape characters. Uncommenting // the next three lines will allow for this issue. //if (get_magic_quotes_gpc()) {  //	$strEmailAddress = stripslashes($strEmailAddress);  //}  // Control characters are not allowed if (preg_match('/[\x00-\x1F\x7F-\xFF]/', $strEmailAddress)) { 	return false; }  // Split it into sections using last instance of "@" $intAtSymbol = strrpos($strEmailAddress, '@'); if ($intAtSymbol === false) { 	// No "@" symbol in email. 	return false; } $arrEmailAddress[0] = substr($strEmailAddress, 0, $intAtSymbol); $arrEmailAddress[1] = substr($strEmailAddress, $intAtSymbol + 1);  // Count the "@" symbols. Only one is allowed, except where  // contained in quote marks in the local part. Quickest way to // check this is to remove anything in quotes. $arrTempAddress[0] = preg_replace('/"[^"]+"/' 								 ,'' 								 ,$arrEmailAddress[0]); $arrTempAddress[1] = $arrEmailAddress[1]; $strTempAddress = $arrTempAddress[0] . $arrTempAddress[1]; // Then check - should be no "@" symbols. if (strrpos($strTempAddress, '@') !== false) { 	// "@" symbol found 	return false; }  // Check local portion if (!$this->check_local_portion($arrEmailAddress[0])) { 	return false; }  // Check domain portion if (!$this->check_domain_portion($arrEmailAddress[1])) { 	return false; }  // If we're still here, all checks above passed. Email is valid. return true;  }  /** * Checks email section before "@" symbol for validity * @param   strLocalPortion	 Text to be checked * @return  True if local portion is valid, false if not */ protected function check_local_portion($strLocalPortion) { // Local portion can only be from 1 to 64 characters, inclusive. // Please note that servers are encouraged to accept longer local // parts than 64 characters. if (!$this->check_text_length($strLocalPortion, 1, 64)) { 	return false; } // Local portion must be: // 1) a dot-atom (strings separated by periods) // 2) a quoted string // 3) an obsolete format string (combination of the above) $arrLocalPortion = explode('.', $strLocalPortion); for ($i = 0, $max = sizeof($arrLocalPortion); $i < $max; $i++) { 	 if (!preg_match('.^(' 					.	'([A-Za-z0-9!#$%&\'*+/=?^_`{|}~-]'  					.	'[A-Za-z0-9!#$%&\'*+/=?^_`{|}~-]{0,63})' 					.'|' 					.	'("[^\\\"]{0,62}")' 					.')$.' 					,$arrLocalPortion[$i])) { 		return false; 	} } return true; }  /** * Checks email section after "@" symbol for validity * @param   strDomainPortion	 Text to be checked * @return  True if domain portion is valid, false if not */ protected function check_domain_portion($strDomainPortion) { // Total domain can only be from 1 to 255 characters, inclusive if (!$this->check_text_length($strDomainPortion, 1, 255)) { 	return false; } // Check if domain is IP, possibly enclosed in square brackets. if (preg_match('/^(25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9]?[0-9])'	.'(\.(25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9]?[0-9])){3}$/'	,$strDomainPortion) ||  	preg_match('/^\[(25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9]?[0-9])'	.'(\.(25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9]?[0-9])){3}\]$/'	,$strDomainPortion)) { 	return true; } else { 	$arrDomainPortion = explode('.', $strDomainPortion); 	if (sizeof($arrDomainPortion) < 2) { 		return false; // Not enough parts to domain 	} 	for ($i = 0, $max = sizeof($arrDomainPortion); $i < $max; $i++) { 		// Each portion must be between 1 and 63 characters, inclusive 		if (!$this->check_text_length($arrDomainPortion[$i], 1, 63)) { 			return false; 		} 		if (!preg_match('/^(([A-Za-z0-9][A-Za-z0-9-]{0,61}[A-Za-z0-9])|' 		   .'([A-Za-z0-9]+))$/', $arrDomainPortion[$i])) { 			return false; 		} 	} } return true; }  /** * Check given text length is between defined bounds * @param   strText	 Text to be checked * @param   intMinimum  Minimum acceptable length * @param   intMaximum  Maximum acceptable length * @return  True if string is within bounds (inclusive), false if not */ protected function check_text_length($strText, $intMinimum, $intMaximum) { // Minimum and maximum are both inclusive $intTextLength = strlen($strText); if (($intTextLength < $intMinimum) || ($intTextLength > $intMaximum)) { 	return false; } else { 	return true; } }  }

And here is the code to use this function

$validator = new EmailAddressValidator; if ($validator->check_email_address($_POST['email'])) { // If it is a valid email then run this section }

I really haven't found any other method that is better for validating email addresses. Give it a try and see what you think!

Share this post


Link to post
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now
Sign in to follow this  

×
×
  • Create New...

Important Information

Terms of Use | Privacy Policy | Guidelines | We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.