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

PhpFile

Php Problem Overview


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?

Php Solutions


Solution 1 - 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.

Solution 2 - Php

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

Solution 3 - Php

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

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionnewbieView Question on Stackoverflow
Solution 1 - PhpMike BView Answer on Stackoverflow
Solution 2 - PhpPYKView Answer on Stackoverflow
Solution 3 - PhpRam PukarView Answer on Stackoverflow