This question is unlikely to help any future visitors; it is only relevant to a small geographic area, a specific moment in time, or an extraordinarily narrow situation that is not generally applicable to the worldwide audience of the internet. For help making this question more broadly applicable, visit the help center.
Closed 9 years ago.
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
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);
}
$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
}
Best way is use file_get_contents & perform 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);
}
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.
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 the it like this also
$content = file_get_contents("titel.txt");
$newvalue = "word-searching";
//Then use strpos to find the text exist or not
you could save all your added string in an array and the check with in_array if the current string has been added or not.
Second choice is to read the file each time you want to write and do a strstr on it.
I believe fgets is the answer here.
$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 have appended a newline ("\n") in your code, which is why fgets will work here. This may be preferable over pulling the whole file into memory with file_get_contents(), simply because the size of the file may be prohibitive of that.
Alternatively, if the values are not newline delimited, but are fixed length, you can always use the $length argument of fgets() to pull exactly $n characters out (or use fread() to pull exactly $n bytes out)
Related
I have a function to write to a .txt file. my problem is that it writes only on the first line, so erases the old line for the new line. I want to append the new lines to the file.
function logit($log,$filename = ''){
$logfile = "log/".date('Ymd').$filename.".txt";
if ($fh = fopen($logfile, 'w')) {
fwrite($fh, date('H:i:s')." | ".$log."\n");
fclose($fh);
return 1;
} else
return false;
}
You need to search before post your question.. there's many documentation and answers for that problem.. anyway, replace this fopen($logfile, 'w') with fopen($logfile, 'a')
I am trying to make a program where I can add things to a list, read things, and clear the list. I have the clear function working perfectly, however I can't seem to add or read more than 1 line at a time. I am using fwrite($handle, $MyString); but that replaces everything in the entire file with $MyString. To get the information from the file I am using $list = fgets($handle); and then using echo to print it. This reads the first line in the file only.
Any help?
Thanks!
Getlist code:
<?php
$myFile = "needlist.txt";
$fh = fopen($myFile, 'r');
$theData = fgets($fh);
fclose($fh);
echo $theData;
?>
Add to the list code:
<?php
$neededlist = "needlist.txt";
$fh = fopen($neededlist, 'w');
$user_message = $_REQUEST['txtweb-message'];
$needed .= $user_message;
$needed .= "\n";
fwrite($fh, $needed);
fclose($fh);
echo "You have successfully added ", $user_message;
?>
When you write to the file are you opening your filehandle with the "a" mode option? Opening with "w" or "x" truncates it so you start with a clean file (http://php.net/fopen)
fgets(); reads only until the end of the line ( http://php.net/fgets ). To get the whole file you can try:
var $list = "";
var $line = "";
while ($line = fgets($handle)) {
$list = $list . "\n" . $line;
}
echo $list;
You want to add the "\n" because fread doesn't read the linefeeds IIRC. There're also a couple functions that might be more appropriate in this situation like file_get_contents and fread.
Fgets returns only one string. You should use it in cycle like that:
while (($buffer = fgets($handle, 4096)) !== false) {
echo $buffer;
}
This question is unlikely to help any future visitors; it is only relevant to a small geographic area, a specific moment in time, or an extraordinarily narrow situation that is not generally applicable to the worldwide audience of the internet. For help making this question more broadly applicable, visit the help center.
Closed 10 years ago.
I am trying to add unknown number of parameters to a string in PHP.
Here is code:
<?php
print "Get parameters";
$myFile = "wr.txt";
$fh = fopen ($myFile, 'w') or die ("can't open file");
$stringData = '';
//$st = '';
foreach ($_REQUEST as $k => $v) {
$date = date ('Y-m-d H:i:s');
$stringData = $k.":".$v."Date:".$date."\n";
fwrite ($fh, $stringData);
fwrite ($fh, $stringData);
fclose ($fh);
}
?>
But it is adding only last parameter value.
I also tried like
$stringData += $k.":".$v."Date:".$date."\n";
And put this:
fwrite($fh, $stringData);
fwrite($fh, $stringData);
fclose($fh);
Outside to the for loop but in that case it is writing 00 in the wr.txt. Please help me how can i write all the paramets in a line by date.
Thanks
In PHP . is used for concatenation + is not used for concatenation.
change this
$stringData +=$k.":".$v."Date:".$date."\n";
to
$stringData .= $k.":".$v."Date:".$date."\n";
Move close ($fh) away from the loop:
$myFile = "wr.txt";
$fh = fopen ($myFile, 'w') or die ("Can't open file");
$date = date ('Y-m-d H:i:s');
foreach ($_REQUEST as $k => $v)
fwrite ($fh, "$k: $v Date $date\n") or die ("Cannot write to file");
fclose ($fh);
use "." instead of "+", in php concatenation operator is "."
SEE THE LINES :
$stringData .=$k.":".$v."Date:".$date."\n";//** ADD CONCATENATION '.' BEFORE '='**
fwrite($fh, $stringData); //PUT THIS OUT SIDE THE LOOP
fwrite($fh, $stringData); //**REMOVE THIS **
fclose($fh); // **PUT HIS OUT SIDE THE FOREACH LOOP**
Try this :
<?php
print "Get parameters";
$myFile = "wr.txt";
$fh = fopen($myFile, 'w') or die("can't open file");
$stringData = '';
//$st = '';
foreach($_REQUEST as $k => $v) {
$date = date('Y-m-d H:i:s');
$stringData .=$k.":".$v."Date:".$date."\n";//** ADD CONCATENATION '.' BEFORE '='**
//fwrite($fh, $stringData); PUT THIS OUT SIDE THE LOOP
///fwrite($fh, $stringData); //**REMOVE THIS **
//fclose($fh); // **PUT HIS OUT SIDE THE FOREACH LOOP**
}
fwrite($fh, $stringData);
fclose($fh);
?>
I can only guess what you are trying to do. but try this:
<?php
print "Get parameters";
$myFile = "wr.txt";
$fh = fopen($myFile, 'w') or die("can't open file");
$stringData = '';
//$st = '';
foreach($_REQUEST as $k => $v) {
$date = date('Y-m-d H:i:s');
$stringData = $stringData . $k.":".$v."Date:".$date."\n";
}
fwrite($fh, $stringData);
fclose($fh);
?>
Hope that helps.
I have an issue with writing and reading to text file.
I have to first write from a text file to another text file some values which I need to read again. Below are the code snippets:
Write to text file:
$fp = #fopen ("text1.txt", "r");
$fh = #fopen("text2.txt", 'a+');
if ($fp) {
//for each line in file
while(!feof($fp)) {
//push lines into array
$thisline = fgets($fp);
$thisline1 = trim($thisline);
$stringData = $thisline1. "\r\n";
fwrite($fh, $stringData);
fwrite($fh, "test");
}
}
fclose($fp);
fclose($fh);
Read from the written textfile
$page = join("",file("text2.txt"));
$kw = explode("\n", $page);
for($i=0;$i<count($kw);$i++){
echo rtrim($kw[$i]);
}
But, if I am not mistaken due to the "/r/n" I used to insert the newline, when I am reading back, there are issues and I need to pass the read values from only the even lines to a function to perform other operations.
How do I resolve this issue? Basically, I need to write certain values to a textfile and then read only the values from the even lines.
I'm not sure whether you have issues with the even line numbers or with reading the file back in.
Here is the solution for the even line numbers.
$page = join("",file("text2.txt"));
$kw = explode("\n", $page);
for($i=0;$i<count($kw);$i++){
$myValue = rtrim($kw[$i]);
if(i % 2 == 0)
{
echo $myValue;
}
}
I'm trying to define an array with a list of file urls, and then have each file parsed and if a predefined string is found, for that string to be replaced. For some reason what I have isn't working, I'm not sure what's incorrect:
<?php
$htF = array('/home/folder/file.extension', '/home/folder/file.extension', '/home/folder/file.extension', '/home/folder/file.extension', '/home/folder/file.extension');
function update() {
global $htF;
$handle = fopen($htF, "r");
if ($handle) {
$previous_line = $content = '';
while (!feof($handle)) {
$current_line = fgets($handle);
if(stripos($previous_line,'PREDEFINED SENTENCE') !== FALSE)
{
$output = shell_exec('URL.COM');
if(preg_match('#([0-9]{1,3}\.){3}[0-9]{1,3}#',$output,$matches))
{
$content .= 'PREDEFINED SENTENCE '.$matches[0]."\n";
}
}else{
$content .= $current_line;
}
$previous_line = $current_line;
}
fclose($handle);
$tempFile = tempnam('/tmp','allow_');
$fp = fopen($tempFile, 'w');
fwrite($fp, $content);
fclose($fp);
rename($tempFile,$htF);
chown($htF,'admin');
chmod($htF,'0644');
}
}
array_walk($htF, 'update');
?>
Any help would be massively appreciated!
Do you have permissions to open the file?
Do you have permissions to write to /tmp ?
Do you have permissions to write to the destination file or folder?
Do you have permissions to chown?
Have you checked your regex? Try something like http://regexpal.com/ to see if it's valid.
Try adding error messages or throw Exceptions for all of the fail conditions for these.
there's this line:
if(stripos($previous_line,'PREDEFINED SENTENCE') !== FALSE)
and I think you just want a != in there. Yes?
You're using $htF within the update function as global, which means you're trying to fopen() an array.
$fh = fopen($htF, 'r');
is going to get parsed as
$fh = fopen('Array', 'r');
and return false, unless you happen to have a file named 'Array'.
You've also not specified any parameters for your function, so array_walk cannot pass in the array element it's dealing with at the time.