Php 找到字符串或将字符串添加到文件时返回消息

Php 找到字符串或将字符串添加到文件时返回消息,php,fopen,fwrite,Php,Fopen,Fwrite,我想检查文本文件中是否存在字符串,如果存在,则返回消息string exists。如果该字符串不存在,请将其添加到文件中并返回string added 我让它在没有任何信息的情况下工作: <?php $path = '../test/usersBlacklist.txt'; $input = $_POST["id"]; if ($input) { $handle = fopen($path, 'r+'); while (!feof($handle)) {

我想检查文本文件中是否存在字符串,如果存在,则返回消息
string exists
。如果该字符串不存在,请将其添加到文件中并返回
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)将始终为true。

如@NigelRen所述,请使用来自的答案,然后使用此选项附加:

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+”可供阅读和写作;将文件指针放在文件末尾。如果文件不存在,请尝试创建它。在此模式下,fseek()仅影响读取位置,写入操作始终附加

更多信息请点击此处:

正如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"
 }

在函数外部使用
return
没有什么意义。如果(真的)当然总是真的,因为,嗯……真的是真的。您希望使用变量来存储状态,然后在if中检查该变量。去读一读什么是退出循环的正确方法。提供了一种更好的方法来检查字符串是否在文件中,您只需在其周围添加正确的逻辑即可。只需编写相同的内容:)可能重复的非完全重复。如果找不到,也要求追加函数
doesLineExist()
如果行不存在,则返回true;如果行不存在,则返回false。这似乎是错误的方法。更重要的是,对于一个方法来说,这是一个正确的名称,是的,但我只是用他的代码示例来演示如何做到这一点。由他来改变它,使之更适合他。是的,我会使用它,就像行exist返回true一样