title: Append at the beginning of the file in PHP
body: <p>Hi I want to append a row at the beginning of the file using php.</p>
  
  <p>Lets say for example the file is containing the following contnet:</p>
  
  <pre><code>    Hello Stack Overflow, you are really helping me a lot.
  </code></pre>
  
  <p>And now i Want to add a row on top of the repvious one like this:</p>
  
  <pre><code>    www.stackoverflow.com
      Hello Stack Overflow, you are really helping me a lot.
  </code></pre>
  
  <p>This is the code that I am having at the moment in a script.</p>
  
  <pre><code>    $fp = fopen($file, 'a+') or die("can't open file");
      $theOldData = fread($fp, filesize($file));
      fclose($fp);
  
      $fp = fopen($file, 'w+') or die("can't open file");
      $toBeWriteToFile = $insertNewRow.$theOldData;
      fwrite($fp, $toBeWriteToFile);
      fclose($fp);
  </code></pre>
  
  <p>I want some optimal solution for it, as I am using it in a php script. Here are some solutions i found on here:
  <a href="https://stackoverflow.com/questions/1760525/need-to-write-at-beginning-of-file-with-php">Need to write at beginning of file with PHP</a></p>
  
  <p>which says the following to append at the beginning:</p>
  
  <pre><code>    &lt;?php
      $file_data = "Stuff you want to add\n";
      $file_data .= file_get_contents('database.txt');
      file_put_contents('database.txt', $file_data);
      ?&gt;
  </code></pre>
  
  <p>And other one here:
  <a href="https://stackoverflow.com/questions/103593/using-php-how-to-insert-text-without-overwriting-to-the-beginning-of-a-text-fil">Using php, how to insert text without overwriting to the beginning of a text file</a></p>
  
  <p>says the following:</p>
  
  <pre><code>    $old_content = file_get_contents($file);
      fwrite($file, $new_content."\n".$old_content);
  </code></pre>
  
  <p>So my final question is, which is the best method to use (I mean optimal) among all the above methods. Is there any better possibly than above?</p>
  
  <p>Looking for your thoughts on this!!!.</p>