fwrite writing from beginning without removing

Posted on

fwrite writing from beginning without removing – Here in this article, we will share some of the most common and frequently asked about PHP problem in programming with detailed answers and code samples. There’s nothing quite so frustrating as being faced with PHP errors and being unable to figure out what is preventing your website from functioning as it should like php and fwrite . If you have an existing PHP-based website or application that is experiencing performance issues, let’s get thinking about fwrite writing from beginning without removing.

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 to the end of the file.

$fr = fopen("aaaa.txt", "a");
fwrite($fr, "text");

Solution :

So you want to write at the beginning of a file, leaving all of its current contents after the new data? You’ll have to grab its existing contents first, then append it back into the file once you’ve overwritten with your new data.

$file = 'aaaa.txt';
$oldContents = file_get_contents($file);
$fr = fopen($file, 'w');
fwrite($fr, "text");
fwrite($fr, $oldContents);

If you want to avoid loading the original file’s contents into memory in your PHP script, you might try first writing to a temp file, using a loop buffer or system calls to append the contents of your original file to the temp file, then remove the original file and rename your temp file.

From the PHP site:


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

I suggest something like this (from php.net site):

$handle = fopen('output.txt', 'r+');

fwrite($handle, 'Really long sentence.');
fwrite($handle, 'Foo');

echo fread($handle, filesize('output.txt'));


$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');
fwrite($fr, $oldContents);

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


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

This should work:

$current = file_get_contents($file);
$user = $_POST["username"];
$pass = $_POST["password"];
file_put_contents($file,$current . "Whatever you want to add here"

This finds the current stuff and copy/pastes it back each time the code is ran (tried to make it as simple as possible in case other answers are a little too complicated)

  1. Open a file in w+ mode not a+ mode.
  2. Get the length of text to add ($chunkLength)
  3. set a file cursor to the beginning of the file
  4. read $chunkLength bytes from the file
  5. return the cursor to the $chunkLength * $i;
  6. write $prepend
  7. set $prepend a value from step 4
  8. do these steps, while EOF

    $handler = fopen('1.txt', 'w+');//1
    $prepend = "I would like to add this text to the beginning of this file";
    $chunkLength = strlen($prepend);//2
    $i = 0;
        $readData = fread($handler, $chunkLength);//4
        fseek($handler, $i * $chunkLength);//5
        fwrite($handler, $prepend);//6
        $prepend = $readData;//7
    }while ($readData);//8

First open the file in c+ mode which opens file or create new file if doesnot exists and points the pointer at beginning of the file. To get old content use file_get_contents and check if the file exists.

$fh = fopen($file_path, 'c+'); 

if (file_exists($file_path)) {   
    $oldContents = file_get_contents($file_path);  
    fwrite($fh,"New Content" );  
    fwrite($fh, $oldContents);   
} else {   
    fwrite($fh,"New Content");   


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

Leave a Reply

Your email address will not be published. Required fields are marked *