How can I overwrite file contents with new content in PHP? - 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

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

fopen() with r+ acts like a?

This is some of the weirdest stuff I've ever honestly seen.
$filename = "/etc/httpd/conf/httpd.conf";
$handle = fopen($filename, "r+");
$size = filesize($filename);
$contents = fread($handle, $size);
fwrite($handle,$contents);
fclose($handle);
Shouldn't this read the contents of the file then write it again? Basically leaving the file unmodified? At this moment this piece of code does exactly what append does, it duplicates the contents of the file adding $contents at the end of the file, and I have no idea why. I tried changing the string a little before writing it and that's how I found out it writes to the end, not the beginning.
Your fread() is advancing the file pointer such that by the time you call fwrite, your file pointer is at the end and your write appends to the file from there.
If you want to write to the file starting at the beginning after reading it all in then:
rewind($handle);

Fwrite save a null file

I have a code in which should open an existing text file into my server, save the text into a variable, then filter the text contained within this variable and save again, as you can see below:
Text File:
Descrição: lorem impsum is a dollar do dolla do dolla style user humam
Source Code:
$filename = "prods/".$value;
$handle = fopen($filename, "w+");
$contents = fread($handle, filesize($filename));
$newcontent .= str_replace("Descrição:", "Descricao:", $contents);
fwrite($handle,$newcontent);
fclose($handle);
The problem is the command write is saving the file again with null text inside him, how can I solve this?
According to http://php.net/manual/en/function.fopen.php:
'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.
You are therefore reading an empty string, and writing such a string back too.
The simplest way to solve your problem might be:
$filename = "prods/".$value;
$contents = file_get_contents($filename);
$newcontent .= str_replace("Descrição:", "Descricao:", $contents);
file_put_contents($filename, $newcontent);
Your problem is the mode 'w+' you use for fopen.
I think a+ is the one you're looking for.
w+ mode truncates the file to 0 length. You want to use c+ or file_get_contents(), then file_put_contents() instead.

Why does fopen('file.txt', 'r+') followed by write() truncate the file?

I test this PHP code on windows and it first removes the file.txt contents and then write the new contents on it.
$f = fopen('file.txt', 'r+');
fwrite($f, "first-time");
fclose($f);
Every time I execute this code and see file.txt, it has ONE "first-time" in it.
I expect it to prepend "first-time" to the old file. like:
first-timefirst-timefirst-time and so on.
Why r+ acts like w+ in making zero length?
Answer to your question: Your code does not truncate the file, but simply overwrites the previous content.
Quick and dirty solution for the behaviour your want to achieve:
<?php
$file_data = "Stuff you want to add\n";
$file_data .= file_get_contents('file.txt');
file_put_contents('file.txt', $file_data);
?>
EDIT:
The answer can be found here:
How do I prepend file to beginning?
According to the PHP fopen manual:
'r+' Open for reading and writing; place the file pointer at the beginning of the file.
'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.
$f = fopen('file.txt', 'a+');
fwrite($f, "fisrt-time");
fclose($f);
So if you'd like to append content, use a+ mode.

How to clear a text file ready for fwrite

I have a text file that is being written with fwrite, how would I delete all the contents of this text file so that I can write onto it a fresh. I've tried to find another function but with no luck.
Example code I am using, I want to clear it before I enter this information:
$string = ', {"key": "'.$info['Name'].'", "value": "'.$info['Name'].'"}';
$fp = fopen('data_old.txt', 'a');
fwrite($fp, $string);
fclose($fp);
If you look at the PHP documentation for fopen, you will see the list of "modes" available in the second parameter. You are passing "a" which means append. You want to pass "w" which means "write".
'a' Open for writing only; place the file pointer at the end of the file. If the file does not exist, attempt to create it.
'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.
You can change your mode parameter in fopen:
$fp = fopen('data_old.txt', 'w+');
By the way, I used w+ in case you want to read from it as well, for just writing you can use w.
Use the w option instead of the a option in fopen.
like fopen('file.txt','w');
this puts the pointer at the beginning of the file instead of the end
http://php.net/manual/en/function.fopen.php
To overwrite an existing file use the write only mode with fopen, which will open the file for writing and set the point to the beginning of the file and also truncate the file to zero length:
$string = ', {"key": "'.$info['Name'].'", "value": "'.$info['Name'].'"}';
$fp = fopen('data_old.txt', 'w');
fwrite($fp, $string);
fclose($fp);
You can do this another way
$file_destination = "./your_text_file_name.txt";
unlink($file_destination);
$your_data = "ABCabc";
$handle = fopen ($file_destination, "a+");
fputs($handle, $your_data);
fclose($handle);

Categories