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

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

Posted by: admin November 30, 2017 Leave a comment

Questions:

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?

Answers:

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.

Questions:
Answers:
$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);

Questions:
Answers:

Alternatively if you have full control of your server, why not “guarantee” the operation tweaking it around by removing the file before?

$wait=exec('rm -r -f myfile.txt');
file_put_contents('myfile.txt','new content');

The $wait here is just to hold the remove command until it gets done