2015-11-02 46 views
1

所以我试图收集和存储电子邮件地址的文本文件,并且正在工作,而不是它不承认如果地址已经提交。它会为文本文件添加一个地址,即使它已经存在。感谢您的见解。为什么strpos()在搜索这个.txt文件时不工作?

<?php 
function showForm() { 
    echo ' 
    <form method="post" action=""> 
    Email Address: <input type="email" name="email"> <br /> 
    <input type="submit" value="Submit" name="submit"> 
    </form> 
    '; 
} 

if(empty($_POST['submit']) === false) { 
    $email = htmlentities(strip_tags($_POST['email'])); 

    $logname = 'email.txt'; 
    $logcontents = file_get_contents($logname); 
$pos = strpos($logcontents, $email); 

if ($pos === true) { 
     die('You are already subscribed.'); 
    } else { 
     $filecontents = $email.','; 
     $fileopen = fopen($logname,'a+'); 
     $filewrite = fwrite($fileopen,$filecontents); 
     $fileclose = fclose($fileopen); 
     if(!$fileopen or !$filewrite or !$fileclose) { 
      die('Error occured'); 
     } else { 
      echo 'Your email has been added.'; 
     } 
    } 
} else { 
    showForm(); 
} 

?> 
+0

email.txt包含? –

+1

'$ pos'可以是'false'或是一个整数值。它不会返回布尔值true。你的'if'具体而严格地检查$ pos是一个布尔值true,它永远不会。 –

回答

1

您此行:找到字符串的

$pos = strpos($logcontents, $email); 

回报位置,而不是布尔值。

AND

if ($pos === true) { 

可以含有作为0位置。

你应该更改为:

if ($pos != false) { 

Reference

3

strpos()返回该串已被发现,或false位置。

检查$pos === true永远不会成功,因为strpos()的返回值不能为true

改为尝试if ($pos !== false) { ...

+0

啊是的!愚蠢的错误谢谢大家。这工作魅力:) – withjamin

0

strpos永远不会返回true。它可以返回位置零,这将被PHP解释为假,除非你使用严格的比较。

if ($pos !== false)