Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Php append to file if the string is unique [closed]

Tags:

file

php

append

Is it possible to check if the string that is being added to file is not already in the file and only then add it? Right now I am using

        $myFile = "myFile.txt";
    $fh = fopen($myFile, 'a') or die("can't open file");
    $stringData = $var . "\n";
    fwrite($fh, $stringData);
    fclose($fh);

But I get many duplicates of $var values and wanted to get rid of them. Thank you

like image 581
user2130729 Avatar asked Mar 07 '13 11:03

user2130729


1 Answers

use this

$file = file_get_contents("myFile.txt");
if(strpos($file, $var) === false) {
   echo "String not found!";
   $myFile = "myFile.txt";
   $fh = fopen($myFile, 'a') or die("can't open file");
   $stringData = $var . "\n";
   fwrite($fh, $stringData);
   fclose($fh);
}
like image 71
Yogesh Suthar Avatar answered Nov 06 '22 17:11

Yogesh Suthar