在将其编入textfile php之前检查值是否存在

时间:2015-10-05 12:29:24

标签: php jquery ajax

我将用户名和用户ID添加到页面的文本文件onload中,如下所示:

$.post("addusersonload.php", {userid:chatusrid,username:chatusrname}, function (data) { 

  });

addusersonload.php

$name = $_REQUEST['username'];
$usrid = $_REQUEST['userid'];

fwrite(fopen('addusersonload.txt', 'a'), "$usrid,$name\n"); 

我在文本字段中获取值如下:

UserA, 1
UserB, 2
UserA, 1
UserB, 2

我想在写入之前检查文本文件是否存在相同的值。因此不会发生重复!!

2 个答案:

答案 0 :(得分:1)

我想数据库是您需要的最佳选择,但是,如果您确实需要写入文件,可以使用:

if(!empty($_POST['username']) and !empty($_POST['userid'])){
    $log_file = "sum_file.txt";
    $logContent = file_get_contents("sum_file.txt");

    $user = $_POST['username'];
    $userId = $_POST['userid'];

    if (!preg_match("/($user),\\s+($userId)\$/m", $logContent)) {
        file_put_contents($log_file, "$user, $userId", FILE_APPEND);
}

}

答案 1 :(得分:0)

我个人建议你使用db,但我仍然可以帮助你..你应该使用json这个

function writeToFile($filename, $msg)
 { 
   $msgArray=array();
   if(file_exists($filename))
        {
        $arrMsg=json_decode(file_get_contents($filename),true);
        if($msg['userId']==$arrmsg['userId'])
              die('already there'); //checking done
        foreach ($arrMsg as $ob)
          {
             array_push($msgArray,$ob);
          }
        unlink($filename);
        }
   array_push($msgArray,$msg);
   $msgArrayJSON=json_encode($msgArray);
   // open file
   $fd = fopen($filename, "a");
   // write string
   fwrite($fd, $msgArrayJSON. PHP_EOL);
   // close file
   fclose($fd);
}

通过使用上述功能,您可以添加像

这样的用户
writeToFile('user.json', array("userId"=>$id,"userName"=>$name));

最后,您可以从文件中获取用户,如下所示

$user_array=json_decode(file_get_contents('user.json'),true);