简体   繁体   中英

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 .

Checking $pos === true can never succeed because the return value of strpos() cannot be true .

Try if ($pos !== false) { ... instead.

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.

You should change this to:

if ($pos != false) {

Reference

strpos won't ever return true. It can return position zero which will be interpreted by PHP as false unless you use strict comparison.

if ($pos !== false)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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