How to add additional text to file php - php

This is my code:
$open = fopen('emails.txt', 'w+');
if ($open) {
$content = "$first $last <$email>,";
if (fwrite($open, $content)) {
// ...
}
}
However, when I run this, it just replaces the text I already have in the file. How do I just add to the file, instead of replacing it?

You have to open the file in append mode, by passing a as the second parameter to fopen():
$open = fopen("emails.txt", 'a');
Then, data you write to the file will be appended to the end of the file, preserving data that was previously written to the file.

If you're only appending one block of text into the file at every request, you could look into file_put_contents() as well:
file_put_contents('emails.txt', $content, FILE_APPEND);
Shorter than having to write fopen(), fwrite() and fclose(), though the latter is more or less optional :)

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

Why does it remove the content of the file?

I've been getting irritated by this bug, and I've tried to fix it but it's been a struggle for me. So I have a php file write to a .txt file, but as I enter different info, it replaces the info that was already in the file, but I don't want it to do that. I want it to add on. Help?
<?php
$filenum = echo rand();
$info = $_GET["info"]; //You have to get the form data
$file = fopen('$filenum.txt', 'w+'); //Open your .txt file
$content = $info. PHP_EOL .$gain. PHP_EOL .$offset;
fwrite($file , $content); //Now lets write it in there
fclose($file ); //Finally close our .txt
die(header("Location: ".$_SERVER["HTTP_REFERER"]));
?>
You're using w+ mode, and the documentation clearly says:
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.
If you want to append, you should use a or a+.
BTW, I'm not nor sure why you're using w+ rather than just w, since you're never reading the file.
Also, you can do it all in one statement using file_put_contents()
$filenum = rand();
$info = $_GET['info'];
$content = $info . PHP_EOL . $gain . PHP_EOL . $offset . PHP_EOL;
file_put_contents("$filenum.txt", $content, FILE_APPEND);
die(header("Location: " . $_SERVER['HTTP_REFERER']));
And notice that you should have PHP_EOL at the end of $content. Otherwise, every time you add to the file, it will start on the same line as the last line you added previously.
I don't know the solution but I would recommend you to see the file format you are opening in, I think it should be 'a+' or something like that which opens file for appending rather than 'w+'. I haven't used php much but I think that's the case

How can I overwrite file contents with new content in PHP?

I tried to use fopen, but I only managed to append content to end of file. Is it possible to overwrite all contents with new content in PHP?
Use file_put_contents()
file_put_contents('file.txt', 'bar');
echo file_get_contents('file.txt'); // bar
file_put_contents('file.txt', 'foo');
echo file_get_contents('file.txt'); // foo
Alternatively, if you're stuck with fopen() you can use the w or w+ modes:
'w' Open for writing only; 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.
'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.
$fname = "database.php";
$fhandle = fopen($fname,"r");
$content = fread($fhandle,filesize($fname));
$content = str_replace("192.168.1.198", "localhost", $content);
$fhandle = fopen($fname,"w");
fwrite($fhandle,$content);
fclose($fhandle);
MY PREFERRED METHOD is using fopen,fwrite and fclose [it will cost less CPU]
$f=fopen('myfile.txt','w');
fwrite($f,'new content');
fclose($f);
Warning for those using file_put_contents
It'll affect a lot in performance, for example [on the same class/situation] file_get_contents too: if you have a BIG FILE, it'll read the whole content in one shot and that operation could take a long waiting time

Insert line on the fly in a file with PHP

I want to make a .php file downloadable by my users.
Every file is different from an user to another:
at the line #20 I define a variable equal to the user ID.
To do so I tried this: Copy the original file. Read it until line 19 (fgets) then fputs a PHP line, and then offer the file to download.
Problem is, the line is not inserted after line 19 but at the end of the .php file. Here is the code:
if (is_writable($filename)) {
if (!$handle = fopen($filename, 'a+')) {
echo "Cannot open file ($filename)";
exit;
}
for ($i = 1; $i <= 19; $i++) {
$offset = fgets($handle);
}
if (fwrite($handle, $somecontent) === FALSE) {
exit;
}
fclose($handle);
}
What would you do ?
append mode +a in fopen() places the handle's pointer at the end of the file. Your fgets() loop will fail as there's nothing left to read at the end of the file. You're basically doing 19 no-ops. Your fwrite will then output your new value at the end of the file, as expected.
To do your insert, you'd need to rewind() the handle to the beginning, then do your fgets() loop.
However, if you're just wanting people to get this modified file, why bother doing the "open file, scan through, write change, serve up file"? This'd leave a multitude of near-duplicates on your system. A better method would be to split your file into two parts, and then you could do a simple:
readfile('first_part.txt');
echo "The value you want to insert";
readfile('last_part.txt');
which saves you having to save the 'new' file each time. This would also allow arbitrary length inserts. Your fwrite method could potentially trash later parts of the file. e.g. You scan to offset "10" and write out 4 bytes, which replaces the original 4 bytes at that location in the original file. At some point, maybe it turns into 5 bytes of output, and now you've trashed a byte in the original and maybe have a corrupted file.
The a+ mode means:
'a+' 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.
You probably want r+
'r+' Open for reading and writing; place the file pointer at the beginning of the file.
Put your desired code in one string variable. Where you will have %s at point where you want to customize your code. After that just respond with php MIME type.
eg;
$phpCode = "if (foo == blah) { lala lala + 4; %s = 5; }", $user_specific_variable;
header('Content-type: text/php');
echo $phpCode;
Voila.
NB: Maybe mime type is not correct, I am talking out of my ass here.
I think instead of opening the file in "a+" mode, you should open the file in "r+" mode, because "a" always appends to the file. But I think the write will anyways overwrite your current data. So, the idea is that you'll need to buffer the file, from the point where you intend to write to the EOF. Then add your line followed by what you had buffered.
Another approach might be to keep some pattern in your PHP file, like ######. You can then:
1. copy the original PHP script
2. read the complete PHP script into a single variable, say $fileContent, using file_get_contents()
3. use str_replace() function to replace ###### in $fileContent with desired User ID
4. open the copied PHP script in "a" mode and rewrite $fileContent to it.

Small editing to my php code that adds a string at the beginning of files

The following code supposed to add at the beginning of my php files on the webserver the string abcdef.
However it replaces all the content with the abcdef. How can I correct it?
Also how can I add something on the end instead of the beginning?
foreach (glob("*.php") as $file) {
$fh = fopen($file, 'c'); //Open file for writing, place pointer at start of file.
fwrite($fh, 'abcdef');
fclose($fh);
}
You just need to open the file with a flag that allows you to write without truncating the file to zero length:
$fh = fopen($file, 'r+');
However it replaces all the content with the abcdef. How can I correct it?
From the documentation for fopen on the "c" mode:
Open the file for writing only. If the file does not exist, it is created. If it exists, it is neither truncated (as opposed to 'w'), nor the call to this function fails (as is the case with 'x'). The file pointer is positioned on the beginning of the file.
When you write 'abcdef' to the file, it will overwrite the first six characters. To prepend text, you'll need to copy the existing content, either by reading it out before writing the additional text, or by:
creating a new file,
writing the new text,
then copying over the old content,
then removing the old file and
renaming the new.
Also how can I add something on the end instead of the begining?
Use the append mode: "a".

Categories