phpstrpos

strpos() != null evaluates as true when it shouldn't


I'm trying to look for the input content (email) within a text file.

So far, the mode works very well if the values are correct, otherwise it seems to go in the state. Let me explain:

I have the variable $email the contents of a possible email, I then a text file containing all the emails separated by a delimiter such as:

email; email; etc ...

at this point with strpos(); I check if the parameter is found in the file, and this works, maybe too much. In particular, if I insert an e-mail that isn't present in the file, the code returning to the message "email found" even if it was not found!

Why does this happen?

$email = "alakey@gmail.com";
$file = file_get_contents("utenti.txt"); //get file contents
if (null != strpos($file, $email))
{
    echo "email found";
} else {
   echo "email was not found!";
}

Solution

  • Change:

    if(null != strpos($file, $email))
    

    to:

    if(false !== strpos($file, $email))
    

    This is because the strpos could be zero so you need to test for false.

    I would also see the comment Fred -ii- made on the question. He makes a very good point.