Php appends to file if line is unique

Is it possible to check if the line added to the file is added to the file and only then add it? I'm using now

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

But I get a lot of duplicate values ​​of $ var and want to get rid of them. Thanks you

+7
source share
7 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); } 
+4
source

The best way is to use file_get_contents and perform the operation only if $ var is not in your file.

 $myFile = "myFile.txt"; $file = file_get_contents($myFile); if(strpos($file, $var) === FALSE) { $fh = fopen($myFile, 'a') or die("can't open file"); $stringData = $var . "\n"; fwrite($fh, $stringData); fclose($fh); } 
+1
source
 $myFile = "myFile.txt"; $filecontent = file_get_contents($myFile); if(strpos($filecontent, $var) === false){ $fh = fopen($myFile, 'a') or die("can't open file"); $stringData = $var . "\n"; fwrite($fh, $stringData); fclose($fh); }else{ //string found } 
+1
source

A possible solution could be:

 1. Fetch the contents using fread or file_get_contents 2. Compare the contents with the current contents in file 3. add it if it is not there. 
0
source
 function find_value($input) { $handle = @fopen("list.txt", "r"); if ($handle) { while (!feof($handle)) { $entry_array = explode(":",fgets($handle)); if ($entry_array[0] == $input) { return $entry_array[1]; } } fclose($handle); } return NULL; } 

You can do it the same

 $content = file_get_contents("titel.txt"); $newvalue = "word-searching"; //Then use strpos to find the text exist or not 
0
source

you could store the whole added row in an array and check with in_array if the current row was added or not.

The second choice is to read the file every time you want to write, and strstr .

0
source

I believe fgets .

 $handle = fopen($path, 'r+'); // open the file for r/w while (!feof($handle)) { // while not end $value = trim(fgets($handle)); // get the trimmed line if ($value == $input) { // is it the value? return; // if so, bail out } // } // otherwise continue fwrite($handle, $input); // hasn't bailed, good to write fclose($handle); // close the file 

This answer is based solely on the fact that you added a new line ( "\n" ) to your code, so fgets will work here. This may be preferable to transferring the entire file to memory using file_get_contents() , simply because the file size may be forbidden.

Alternatively, if the values ​​are not limited to a newline, but are a fixed length, you can always use the $length fgets() argument to pull out only the $n characters (or use fread() to print t26> bytes exactly)

0
source

All Articles