Santhucool
Santhucool

Reputation: 1716

Check value exists or not before wriring it into textfile php

I am adding username and userid into a text file onload of a page as follows:

$.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"); 

I am getting the value in text field as follows:

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

I want to check the textfile that the same value exists or not before writing into it.so that the duplication will not occur!!

Upvotes: 2

Views: 126

Answers (2)

Pedro Lobito
Pedro Lobito

Reputation: 98971

I guess a DB is the best option for what you need, but, if you really need to write to a file, you can use:

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

}

Upvotes: 1

Rohit Kumar
Rohit Kumar

Reputation: 1958

I personally recommend you to use db , but still i may help you .. You should use json for this

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

And by using the above function you may add user like

writeToFile('user.json', array("userId"=>$id,"userName"=>$name));

Finally , you could get users from file as below

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

Upvotes: 0

Related Questions