2015-11-02 44 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)