Return 如果找到字符串或将其添加到文件中则显示消息

Return message if string is found or added added to file

我想检查文本文件中是否存在字符串,如果存在,return 消息 string exists。如果不存在,则将字符串添加到文件中 return string added.

我在没有消息的情况下正常工作:

<?php

$path = '../test/usersBlacklist.txt';
$input = $_POST["id"];

if ($input) {
    $handle = fopen($path, 'r+');

    while (!feof($handle)) {
        $value = trim(fgets($handle));

        if ($value == $input) {
            return false;
        }
    }

    fwrite($handle, $input);
    fclose($handle);
    return true;
}

if (true) {
    echo 'added';
} else {
    echo 'exists';
}

?>

此代码毫无意义,解决方案可能是创建一个函数:

function checkI($input) {
    $handle = fopen($path, 'r+');

    while (!feof($handle)) {
        $value = trim(fgets($handle));

        if ($value == $input) {
            return false;
        }
    }

    fwrite($handle, $input);
    fclose($handle);
    return true;
}

然后:

if (checkI($input)) {
    echo 'added';
} else {
    echo 'exists';
}

你的 if(true) ,它将永远为真。

正如@NigelRen 提到的,使用来自 this question 的答案,然后使用它来附加:

if( strpos(file_get_contents($path),$input) !== false) {
    echo "found it";
}
else{
    file_put_contents($path, $input, FILE_APPEND | LOCK_EX);
    echo "added string";
}

如果你试图将一些值附加到一个已经有一些数据的文件中,那么使用 "a+" 标志而不是 "r+"

会更好

如 php 文档中所述:

'a+' Open for reading and writing; place the file pointer at the end of the file. If the file does not exist, attempt to create it. In this mode, fseek() only affects the reading position, writes are always appended.

更多信息在这里:https://secure.php.net/manual/en/function.fopen.php

而且就像 CBroe 所说的那样,在函数外部使用 return 对您没有帮助,更好的方法是这样的:

$input = $_POST["id"];
function doesLineExist($input){
   $path = '../test/usersBlacklist.txt';  

   if ($input) {
       $handle = fopen($path, 'r+');

       while (!feof($handle)) {
         $value = trim(fgets($handle));

         if ($value == $input) {
           return false;
         }
       }

     fwrite($handle, $input);
     fclose($handle);
     return true;
   }
 }

$doesExist = doesLineExist($input);
if($doesExist){
    echo "Added"
 }else{
   echo "Exists"
 }