Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I prepend file to beginning?

Tags:

file

php

In PHP if you write to a file it will write end of that existing file.

How do we prepend a file to write in the beginning of that file?

I have tried rewind($handle) function but seems overwriting if current content is larger than existing.

Any Ideas?

like image 209
mathew Avatar asked Jul 26 '10 04:07

mathew


People also ask

How do I append to the beginning of a file in bash?

You cannot insert content at the beginning of a file. The only thing you can do is either replace existing content or append bytes after the current end of file.

How do you add a line to the beginning of a file Unix?

If you want to add a line at the beginning of a file, you need to add \n at the end of the string in the best solution above.

How do you add a line at the beginning of a file in shell script?

Add Text to Beginning of File Using echo and cat Commands Then, we simply output the variable and redirect it to the same file. As you can see above, the new text was added on a new line at the beginning of the file. To add the text at the beginning of the existing first line, use the -n argument of echo.


2 Answers

$prepend = 'prepend me please';

$file = '/path/to/file';

$fileContents = file_get_contents($file);

file_put_contents($file, $prepend . $fileContents);
like image 108
alex Avatar answered Oct 06 '22 18:10

alex


The file_get_contents solution is inefficient for large files. This solution may take longer, depending on the amount of data that needs to be prepended (more is actually better), but it won't eat up memory.

<?php

$cache_new = "Prepend this"; // this gets prepended
$file = "file.dat"; // the file to which $cache_new gets prepended

$handle = fopen($file, "r+");
$len = strlen($cache_new);
$final_len = filesize($file) + $len;
$cache_old = fread($handle, $len);
rewind($handle);
$i = 1;
while (ftell($handle) < $final_len) {
  fwrite($handle, $cache_new);
  $cache_new = $cache_old;
  $cache_old = fread($handle, $len);
  fseek($handle, $i * $len);
  $i++;
}
?>
like image 23
ashastral Avatar answered Oct 06 '22 18:10

ashastral