Advanced PHP Form Input Validation to Check User Inputs - Validating Domains for Email Addresses (
Page 3 of 4 )
The function responsible for checking to see if the domain has associated mail exchange records is checkdnsrr () . However, this function is not available on the Windows platform and can cause validation issues for the domain name. It needs to have a Windows-compatible checkdnsrr function. The script below is tested to work in Windows XAMPP, but it is not guaranteed to work in all server platforms.
<?php
// PHP email validation script by Codex M for PHP 5 and compatible with Windows platform.
//This script will accept email address and validate it according to RFC specifications as well as check DNS records for validity.
//Then if found valid will store the email to MySQL database.
//connect to MySQL database
$username = "mysqlusernamehere";
$password = "mysql password here";
$hostname = "localhost";
$table = "email";
$database = "email";
//connection to the database
$dbhandle = mysql_connect($hostname, $username, $password)
or die("Unable to connect to MySQL");
//select a database to work with
$selected = mysql_select_db($database,$dbhandle)
or die("Could not select $database");
if (!$_POST['submit'])
{
//form not submitted
?>
<form action="<?php echo $SERVER['PHP_SELF']; ?>"
method="post">
Email Address:
<br />
<input type="text" name="email" size="50">
<br /><br />
<input type="submit" name="submit" value="Test email according to RFC Specifications and DNS MX records">
</form>
<?php
}
else
{
//form submitted
//check email field
if (!isset($_POST['email']) || trim($_POST['email']) == "")
{
die ('ERROR: Enter email');
}
else
{
$email =$_POST['email'];
//sanitize for illegal characters
$email = mysql_real_escape_string(stripslashes($email));
//check domain name if it exist
$domainname= explode("@",$email);
$checkdomain= $domainname[1];
//Codex-m improve the Windows compatible checking Checkdnsrr function by Hamish Milne
//Start of MX validation
function checkdnsrr($checkdomain, $type='mx'){
$res=explode("n",strstr(shell_exec('nslookup -type='.$type.' '.escapeshellarg($checkdomain).' 4.2.2.3'),"nn"));
if($res[2]){
return TRUE;
}else{
return FALSE;
}
}
function dns_check_record($checkdomain, $type='mx'){
return checkdnsrr($checkdomain, $type);
}
$result = dns_check_record($checkdomain, $type='mx');
}
//End of MX validation
if((!(filter_var($email, FILTER_VALIDATE_EMAIL))) ||(!($result==1)))
{
echo $email.' is NOT a valid email address';
echo '<br />';
echo '<a href="http://localhost/testemail.php">Try again</a>';
}
else
{
echo $email.' is a valid email address';
mysql_query("INSERT INTO `email` (`email`) VALUES('$email')")
or die(mysql_error());
echo '<br />';
echo '<a href="http://localhost/testemail.php">Try again</a>';
}
}
?>