Try this Validation Code - Tests for valid email address
Here is a php function that you can use for validation in your script - place it at the bottom (There are others, of course, and I may have gotten some or all of it from Ilovejackdaniels.com):
Code:
// check to see if email is valid
function validEmail($email) {
$isValid = true;
$atIndex = strrpos($email, "@");
if (is_bool($atIndex) && !$atIndex) { $isValid = false; }
else {
$domain = substr($email, $atIndex+1);
$local = substr($email, 0, $atIndex);
$localLen = strlen($local);
$domainLen = strlen($domain);
if ($localLen < 1 || $localLen > 64) { $isValid = false; } // local part length exceeded
else if ($domainLen < 1 || $domainLen > 255) { $isValid = false; } // domain part length exceeded
else if ($local[0] == '.' || $local[$localLen-1] == '.') { $isValid = false; } // local part starts or ends with '.'
else if (preg_match('/\\.\\./', $local)) { $isValid = false; } // local part has two consecutive dots
else if (!preg_match('/^[A-Za-z0-9\\-\\.]+$/', $domain)) { $isValid = false; } // character not valid in domain part
else if (preg_match('/\\.\\./', $domain)) { $isValid = false; } // domain part has two consecutive dots
else if (!preg_match('/^(\\\\.|[A-Za-z0-9!#%&`_=\\/$\'*+?^{}|~.-])+$/', str_replace("\\\\","",$local))) {
// character not valid in local part unless local part is quoted
if (!preg_match('/^"(\\\\"|[^"])+"$/', str_replace("\\\\","",$local))) { $isValid = false; }
}
if ($isValid && !(checkdnsrr($domain,"MX") || checkdnsrr($domain,"A"))) { $isValid = false; } // domain not found in DNS
}
return $isValid;
}
You use it something like this, so at the top of your php script that gets the data from the html page, it should have:
Code:
<?php
// first clean up the input values
foreach($_POST as $key => $value) {
if(ini_get('magic_quotes_gpc'))
$_POST[$key] = stripslashes($_POST[$key]);
$_POST[$key] = htmlspecialchars(strip_tags($_POST[$key]));
}
Then after that, we test all the input, and if there is something we don't like, we send it to the web browser:
Code:
// test input values for errors
$errors = array();
if(strlen($name) < 2) {
if(!$name) { $errors[] = "You must enter a name."; }
else { $errors[] = "Name must be at least 2 characters."; }
}
if(!$email) { $errors[] = "You must enter an email."; }
else if (!validEmail($email)) { $errors[] = "You must enter a valid email."; }
if($errors) {
// output errors to browser and die with a failure message
$errortext = "";
foreach($errors as $error) {
$errortext .= "<li>".$error."</li>";
}
die("<span class='failure'>The following errors occured:<ul>". $errortext ."</ul></span>");
}
Then, since everything looks good, we can finally send the email! So send it here.