使用PHP检查电子邮件是否存在于txt文件中



我使用此代码检查输入的电子邮件是否存在于文本文件中

$handle = fopen("http://mywebsite/u.txt", "r");
if ($handle) {
while (($line = fgets($handle)) !== false) {
$line = preg_replace('/s+/', ' ', $line);
if($line=$email){
echo "email existe";
}
}
fclose($handle);
} else {
// error opening the file.
}

文本文件中存在电子邮件和不存在电子邮件的输出相同

电子邮件存在电子邮件存在邮件存在

文本文件包含测试电子邮件

  • test@test.com
  • hello@world.com
  • test@t.com

如果我做了==,当$line=$email时,它没有进入条件

尝试

echo $line." ".$email;

输出

test@test.comtest@test.comtest@test.comtest@test.comtest@test.comtest@test.com

您的代码失败有两个原因。

1(if($line=$email)是一种赋值方法,并且将始终为TRUE。您希望使用==比较方法。

2( 您需要使用trim(),因为这将处理文件中包含的换行符。这里的另一位成员Aynber对此进行了概述。为他们喝彩。

依据:

"您可能需要修剪((行和电子邮件,以确保没有空白/新行–aynber">

"放入var_dump($line(;在preg_replace之后,它后面还有一个空间。">

我不知道我是否正确理解了你,但这里你对问题有一个稍微不同的解决方案

// File from http
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, "https://example.com");
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
$handle = curl_exec($ch);
curl_close($ch);   
// or
$handle = file_get_contents("u.txt");
//or
$handle = "test@test.com n hello@world.com";

$find = "hello@world.com";
if (strpos($handle, $find) > -1){ 
echo "Found" ; 
} else{ 
echo "Not Found"; 
} 

最新更新