0

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!";
}
  • 2
    `if` [strpos](http://php.net/manual/en/function.strpos.php)`($hackstack, $needle) !== false) { ... }` – DarkBee Nov 20 '14 at 16:09
  • 1
    strpos does not return null – Steve Nov 20 '14 at 16:11
  • 1
    Sidenote: This isn't the best solution to use. If a search is made for `email@example.comm` it will still consider it as being "found". You're looking to use an exact match instead such as `preg_match()` for instance. – Funk Forty Niner Nov 20 '14 at 16:13

1 Answers1

4

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.

David Jones
  • 4,275
  • 6
  • 27
  • 51
  • Yes now working perfect! Is a my mistake, thanks for all guys :) –  Nov 20 '14 at 16:14
  • Thanks for the mention David. +1 because it does solve OP's present code issue. – Funk Forty Niner Nov 20 '14 at 16:19
  • @Fred-ii- Your welcome! Its an important point that should be taken into consideration – David Jones Nov 20 '14 at 16:32
  • Indeed David. It will be fine if the OP has complete control over the data in the file. If not, then using `preg_match()` with the `\b` boundary would be best. Here's one I found http://stackoverflow.com/q/4722007/ – Funk Forty Niner Nov 20 '14 at 16:34