简体   繁体   English

为什么搜索.txt文件时strpos()不起作用?

[英]Why is strpos() not working when searching this .txt file?

So I am trying to collect and store emails addresses in a text file and is is working other than it not recognising if an address has already been submitted. 因此,我正在尝试将电子邮件地址收集和存储在文本文件中,并且除了无法识别地址是否已提交之外,它还在工作。 It will add an address to the text file even if it is already present. 即使已经存在,也会在文本文件中添加一个地址。 Thank you for your insight. 感谢您的见解。

<?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();
}

?>

strpos() returns the position at which the string has been found, or false . strpos()返回找到字符串的位置,或者返回false

Checking $pos === true can never succeed because the return value of strpos() cannot be true . 检查$pos === true永远不会成功,因为strpos()的返回值不能为true

Try if ($pos !== false) { ... instead. 尝试if ($pos !== false) { ...代替。

Your this line: 您的这一行:

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

returns position of the string found, not boolean value. 返回找到的字符串的位置,而不是布尔值。

AND

if ($pos === true) {

may contain 0 as position. 可能包含0作为位置。

You should change this to: 您应该将其更改为:

if ($pos != false) {

Reference 参考

strpos won't ever return true. strpos永远不会返回true。 It can return position zero which will be interpreted by PHP as false unless you use strict comparison. 它可以返回零位,除非您使用严格的比较,否则PHP会将其解释为false。

if ($pos !== false)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM