php fwrite append not working [closed] - php

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 6 years ago.
Improve this question
Hello I am trying to make a script that is based on HTML post and basic PHP.
I have 1 input on HTML, and I have this PHP code:
<?php echo'h'?>
One of my friends said that if I changed the w to an it would create a new line so I changed it and it is still not working.
Basically what I am trying to do is that when they enter the text box any word, it writes that word to the text document, but the second time it won't create a new line, I just want to create a new line.
Here is my full code:
<?PHP
$file_handle = fopen("sample.txt", "r");
$file_contents = $_POST['f1'];
fwrite($file_handle, $file_contents);
fclose($file_handle);
print "file created and written to";
?>

There is also other seemingly simpler functions by the names: file_put_contents() and file_get_contents(), which could be used (in your case) to make things a little easier to handle. The Code below shows the use of file_put_contents() and it's kin: file_get_contents() to accomplish the task.
<?php
$fileName = "sample.txt";
// GET THE TEXT TYPED-IN BY THE USER...
// ONLY YOU KNOW THE WAY TO GET THIS VALUE BUT WE CAN ASSUME (FOR NOW)
// THAT IT IS COMING FROM THE POST VARIABLE AND HAS THE NAME: input
$input = isset($_POST['input']) ? $_POST['input'] : null;
// FIRST TRY TO SEE IF THE FILE EXIST, OTHERWISE CREATE IT
// HOWEVER; WITH JUST AN EMPTY CONTENT
if(!file_exists($fileName)){
file_put_contents($fileName, "");
}
// DO THE SAVING ONLY IF WE HAVE ANY INPUT (STRING) TO SAVE
if($input){
// GET THE CURRENT CONTENTS OF THE FILE...
$fileContent = file_get_contents($fileName);
// ADD THE INPUT TO THE CURRENT CONTENTS OF THE FILE (WITH A NEW LINE)
$fileContent .= "\n{$input}";
// SAVE THE MODIFIED CONTENT BACK AGAIN...
$bytesSaved = file_put_contents($fileName, $fileContent);
// IF THE FILE WAS SUCCESSFULLY WRITTEN... THEN...
// DISPLAY A MESSAGE TO THAT EFFECT
if($bytesSaved){
print "file created and written";
}
}

I assume you want to add the line that has been posted to a previously stored file? In that case your code would look like this:
$file_handle = fopen("sample.txt", "a"); // append to previous contents
$file_contents = $_POST['f1'] . "\r\n";
fwrite($file_handle, $file_contents);
fclose($file_handle);
print "Content has been appended.";
More about the different fopen() modes can be found in the documentation, chapter "modes" and more about escape sequences (like \r\n) can be found in the Strings chapter.

Related

How can i save all the variable results from a echo into a txt file using php?

I wrote a php script that generates random tokens, and I want to output these tokens into a .txt file.
Below is the code:
do {
$token = bin2hex(random_bytes(2));
echo("token: $token");
$myfile = fopen("output.txt", "w+") or die("Unable to open file!");
fwrite($myfile, $token);
fclose($myfile);
} while ($token != "e3b0");
It echos multiple tokens, until the echo = e3b0, but when I try to write the result on a txt file, it only writes "e3b0", is that a way to write all the results of the "echo" into a txt file?
As I see it the most efficient way to do this would be to do everything just enough times.
Meaning we have to loop and generate the codes, but we only need to write to the file once,same thing with the echo.
$code = "start value";
while ($code != "e3b0"){
$arr[] = $code = bin2hex(random_bytes(2));
}
echo $str = implode("\n", $arr);
file_put_contents("output.txt", $str);
This is do everything just enough times, and a more optimized code.
But if you run this in a browser then it will not output them on separate lines on screen, only in the txt file. But if you open the source it will be on separate lines.
That is because I did not use the br tag in the implode.
EDIT: Efficiency was never asked in original OP question. This post is being edited to include efficiency, namely no need to reopen and close a file.
Your use of w+ will always place the file pointer at the beginning of the file and truncate the file in the process. So as a result, you always end up with the last value written.
From php.net on fopen w+:
Open for reading and writing; place the file pointer at the beginning of the file
and truncate the file to zero length. If the file does not exist, attempt to create it.
Using your existing code, a solution then would be as follows:
$myfile = fopen("output.txt", "a+") or die("Unable to open file!");
do {
$token = bin2hex(random_bytes(2));
echo("token: $token");
fwrite($myfile, $token);
} while ($token != "e3b0");
fclose($myfile);
Where a+ in the same docs says:
Open for reading and writing; place the file pointer at the end of the file.
If the file does not exist, attempt to create it. In this mode, fseek()
only affects the reading position, writes are always appended.
Source:
https://www.php.net/manual/en/function.fopen.php
Amendments:
As #andreas mentions, opening and closing the file repeatedly inside the loop is not necessary (nor efficient). Since you are appending, you can open it once with a+ before the loop begins; and close it after the loop ends.
In terms of having a separator char between tokens written to the file, a carriage return (line break) is a good choice. In this way you can reduce the amount of parsing you would have to program when programmatically reading the file. For this, your writes could be written as follows:
fwrite($myfile, $token . "\n");

How to delete array in text file PHP

I have a text file. I want to delete some lines with a query of search.
The array is line by line. I want to made it like http://keywordshitter.com/
The logic is,
SEARCH --> IN ARRAY --> OUTPUT IS ARRAY WITHOUT "QUERY OF SEARCH"
Code I have tried:
$fileset = file_get_contents("file.txt");
$line = explode("\n", $fileset);
$content = array_search("query",$line);
print_r($content);
MY file.txt
one
two
three
apple
map
I have used array_search but not working.
you can do search like
$fileset=file("file.txt"); // file function reads entire file into an array
$len=count($fileset);
for($i=0;$i<$len;$i++)
{
if($fileset[$i]=="query")
{
$fileset[$i]="";
break; //then we will stop searching
}
}
$fileset_improve=implode($fileset); //this will again implode your file
$handle=fopen("file.txt","w"); //opening your file in write mode
fwrite($handle,$fileset_improve); //writing file with improved lines
fclose($handle); //closing the opened file
remember this lines will make your search line blank....
if you wanna then you can arrange whole array i.e. shifting following indexed data to previous index to decrease line counts but this will increase your programming complexity.
Hope this will work for you.
Thanks
Use PHP_EOL on your explode function instead of "\n". PHP_EOL will handle the correct line break character(s) of the server platform.

How to get a specific line with fgets() or fgetss()

I want to know how I would read a specific line (or even specific character) with fgets() or fgetss().
In example;
data.txt-
this is data 1
this is data 2
this is data 3
How would I read only data 2?
If it's possible, that is.
Also, how can I only read the last line? Like if I were to use a+ to write at the end of the file, it'd be the newest content.
Another question:
Is it possible to read through the whole file and check if something exists? If so, how?
Thanks in advance!
For text file:
$fileName = 'file.txt';
$file = new \SplFileObject($fileName);
$file->setFlags(\SplFileObject::READ_CSV);
$seek = 1;
$file->seek($seek);
$line = $file->fgets();
In $line variable has second line from file.

Using txt files as a log for quiz answers (php)

I have a php file that writes to a txt file:
<?php
$answers = "answers.txt";
$fh = fopen($answers, 'a+') or die("can't open file");
$stringData = $_POST["username"];
$timestamp = date("g:i A, m/j/Y");
fwrite($fh, $stringData);
fwrite($fh, " started the quiz at ");
fwrite($fh, $timestamp);
fwrite($fh, "\n");
fclose($fh);
?>
Assuming I replace this code to enter a number (e.g. 10) followed by the user's answer (a string) so it submits the question number followed by the answer, how can I search through the txt file for the username then add that line to an array? Also, could I check the file when each question loads to see which questions the user has answered and then either choose another random quiz or continue loading (if they have not)?
Basically:
Search the text file for a string and output any lines that contain it
Search the text file for a string and then search for a number encased in commas or some other identifier (e.g. ,23,) on the same line as the string.
If I should be doing this using MySQL, a few links or other resources would be nice, because I have heard of MySQL but never used it.
Thanks a bunch in advance!
NOTE: I believe I need to search for a string using strpos and then get the line number and take the whole line and put it in the string. Then, I need to use explode "," to get the question numbers and have a php script on each page check to see if it's number has already been answered. If so, then select another random number. If not, recieve input then write it back to the text file. Or, perhaps I could use sessions to store the questions answered. However, I have no idea how to implement all this together.
I would say MySQL would be the better route to take.
Get Started Here: http://www.w3schools.com
Also check out other posts here:
MySql database design for a quiz
Am doing online Quiz type of script in PHP. It is better to use cookies or sessions
EDIT:
Don't forget about security!

Problems with replacing text in a text file

I have the following scenarion.
Everytime my page loads I create a file. Now my file has two tags within. {theme}{/theme} and {layout}{/layout}, now everytime I choose a certain layout or theme it should replace the tags with {layout}layout{/layout} and {theme}theme{/theme}
My issue is that after I run the following code
if(!file_exists($_SESSION['file'])){
$fh = fopen($_SESSION['file'],"w");
fwrite($fh,"{theme}{/theme}\n");
fwrite($fh,"{layout}{/layout}");
fclose($fh);
}
$handle = fopen($_SESSION['file'],'r+');
if ($_REQUEST[theme]) {
$theme = ($_REQUEST[theme]);
//Replacing the theme bracket in the cache file for rememberence
while($line=fgets($handle)){
$line = preg_replace("/{theme}.*{\/theme}/","{theme}".$theme."{/theme}",$line);
fwrite($handle, $line);
}
}
My output looks as follows
{theme}{/theme}
{theme}green{/theme}
And it needs to look like this
{theme}green{/theme}
{layout}layout1{/layout}
I rarely use random-access file operation but like to read it all as text and write ti back so I might be wrong here. BUT as I can see, you read the first line (so the pointer is at the beginning of the second line). Then you write '{theme}green{/theme}' into that file so it replaces the next position text (the second line).
In this case (as your data is small), you better get the hold file. Change it as string and write it back.

Categories