I am using PHP and fwrite code, but I want every write position to start from the beginning of the file without erasing it\'s content. I am using this code but it is writing
Prefetching old content with file_get_contents and appending it after writing new content is one way to do it. But In case, the file is being dynamically written and along the way you needed to go back to the beginning of file and add some text, then here is how:
$handle = fopen($FILE_PATH, 'w+');
fwrite($handle, "I am writing to a new empty file
and now I need to add Hello World to the beginning");
to prepend Hello World do the following:
$oldText = '';
fseek($handle, 0);
while (!feof($handle)) {
$oldText .= fgets($handle);
}
fseek($handle, 0);
fwrite($handle, "Hello World! ");
fwrite($handle, $oldText);
fclose($handle);
The result would be:
Hello World! I am writing to a new empty file and now I need to add Hello World to the beginning
Reminder and like Fabrizio already noted:
If you have opened the file in append ("a" or "a+") mode, any data you write to the file will always be appended, regardless of the file position
$file = 'aaaa.txt';
$tmp = file_get_contents($file);
$tmp = 'text'.$tmp;
$tmp = file_put_contents($file, $tmp);
echo ($tmp != false)? 'OK': '!OK';
use this code :
$file = 'aaaa.txt';
$oldContents = file_get_contents($file);
$fr = fopen($file, 'w');
$newmsg="text".$oldContents;
fwrite($fr, $oldContents);
fclose($fr);
From the PHP site:
Note:
If you have opened the file in append ("a" or "a+") mode, any data you write to the file will always be appended, regardless of the file position
I suggest something like this (from php.net site):
$handle = fopen('output.txt', 'r+');
fwrite($handle, 'Really long sentence.');
rewind($handle);
fwrite($handle, 'Foo');
rewind($handle);
echo fread($handle, filesize('output.txt'));
fclose($handle);
do these steps, while EOF
$handler = fopen('1.txt', 'w+');//1
rewind($handler);//3
$prepend = "I would like to add this text to the beginning of this file";
$chunkLength = strlen($prepend);//2
$i = 0;
do{
$readData = fread($handler, $chunkLength);//4
fseek($handler, $i * $chunkLength);//5
fwrite($handler, $prepend);//6
$prepend = $readData;//7
$i++;
}while ($readData);//8
fclose($handler);
Use fseek() to set your position in the file.
$fr = fopen("aaaa.txt", "r+");
fseek($fr, 0); // this line will set the position to the beginning of the file
fwrite($fr, "text");
fclose($fr);