0

I have a PHP script that runs when a form button is clicked. Everything is working fine, apart from a routine that checks for email format. I have tried using the inbuilt PHP filter function for that but it doesnt even seem to run (I am using a suitable version of PHP for this). I am checking for the existence of the 'at' symbol and a dot for the domain name, just on the dev machine WAMP webserver at the moment. If I enter an invalid address (say abc123 - i.e., no 'at' symbol, no dot) it seems to think everything is OK and loads the appropriate page. Code here: (tempvar echoes correctly by the way, and is just there for experiment)

$_SESSION['emailaddress']=$_POST['unamebox'];
$tempvar = $_SESSION['emailaddress'];
function checkEmail($tempvar) {
   $find1 = strpos($tempvar, '@');
   $find2 = strpos($tempvar, '.');
   return ($find1 !== false && $find2 !== false && $find2 > $find1);
}

if ( checkEmail($tempvar) ) 
{
   echo "OK";
}
else
{
    echo "Bad email format!";
}
  • `abc123` gives `Bad email format!`. Please provide more info. Do you start the session? https://3v4l.org/5M9eY – user3783243 Dec 15 '20 at 13:41
  • 1
    Don't do this manually Just use [filter_var()](https://www.php.net/manual/en/function.filter-var.php) (there's an example for validating emails on that page). What a valid email is isn't as clear cut as you might think. It's also valid to have `.` in the name (the part before the `@` ), which you don't allow. – M. Eriksson Dec 15 '20 at 13:41
  • 2
    " I have tried using the inbuilt PHP filter function for that but it doesnt even seem to run" Can you expand on this? What I also see - addresses like "stack.overflow@example.com" will be seen as invalid – Sindhara Dec 15 '20 at 13:41
  • 3
    Why reinvent the wheel? https://stackoverflow.com/a/64175650/5827005 – GrumpyCrouton Dec 15 '20 at 13:42
  • I did use filter_var (that was the inbuilt function I referred to. Sorry, should have mentioned it explicitly) – Michael Poxon Dec 15 '20 at 19:55

1 Answers1

0

Because strpos return an integer if found the template in string otherwise return false. Now the !== operator is also match variable types!

When find1 or find2 strpos is match, the !== return false value!

adampweb
  • 1,135
  • 1
  • 9
  • 19