-1

I'm trying to create a script that validates syntax and MX Record to know if the email is correct.

But for some reason this isn't correct.

Any ideas?


My TXT file:

email@facebook.com

email@gmail.com

asdhiadf@fdfsdf.com


My PHP Code:

$fh = fopen('emails.txt','r');
while ($line = fgets($fh)) {

// 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, $line))
{
    list($username,$domaintld) = split("@",$line);
    // Validate the domain
    if (getmxrr($domaintld,$mxrecords)) {
        echo(1) . "--> " . $line . "<br />";
    }
    else {
        echo (-1) . "--> " . $line . "<br />";
    }
} else {
    echo(0) . "--> " . $line . "<br />";
}

}
fclose($fh);
user3629180
  • 27
  • 10

3 Answers3

2

Apart from all of the comments below your question that you should take into account, the reason your code fails, is because of fgets().

When you read a line with fgets() a new-line character will exist at the end of every line except for the last one, so both your regex and filter_var() will always fail except for the last e-mail address (if you don't have an empty line after that...).

To solve the current problem, you need:

while ($line = fgets($fh)) {
  $line = trim($line);
jeroen
  • 91,079
  • 21
  • 114
  • 132
2

The reason you're getting this problem is the \n character at the end of each line.

Try removing it like this:

while ($line = fgets($fh)) {
  $line = substr($line, 0,-1);
Funk Forty Niner
  • 74,450
  • 15
  • 68
  • 141
Younes Regaieg
  • 4,156
  • 2
  • 21
  • 37
1

Use preg_match to evaluate regex, and use explode to split

if(preg_match("/^([_a-z0-9-])([\._a-z0-9-]+)*@([a-z0-9-])([\.a-z0-9-]+)*(\.[a-z]{2,4})$/"),trim($email)){
     explode("@",$email);
}
Funk Forty Niner
  • 74,450
  • 15
  • 68
  • 141
CMPS
  • 7,733
  • 4
  • 28
  • 53